For loop for an array in bash - arrays

If I want to print out the contents from the 13 element till the second last element of an array and I don't know how long the array is, is this how it would be done with BASH?
for array_element in `seq 13 $(({myarray[#]-1))`
do
echo ${myarray[array_element]}
done

Since you're using bash, don't use seq. Instead, use a C-style for loop.
for ((i=13; i < ${#myarray[#]} - 1; i++)); do
echo ${myarray[i]}
done

You could do it like this:
for array_element in `seq $((${#myarray[#]}-1))`
do
echo ${myarray[$((array_element-1))]}
done

Related

why it does not start from the first line of array?

code:
#!/bin/bash
aa=(1 2 3 4)
for i in "${aa[#]}";do
echo "${aa[$i]}"
done
exit 0
it will prints out:
2
3
4
i dont think theres an error in my code, I already double checked it with shellcheck too.
The loop iterates over the array's values, not its indices. It'll be clearer if you make the array values strings:
aa=(foo bar baz quux)
for entry in "${aa[#]}";do
echo "$entry"
done
Notice how I got rid of the aa[$i] lookup and just print the variable directly. This prints:
foo
bar
baz
quux
If you want to iterate over the indices add !:
for i in "${!aa[#]}";do
echo "${aa[$i]}"
done
Or use a C-style loop:
for ((i = 0; i < "${#aa[#]}"; i++)); do
echo "${aa[$i]}"
done

Loop through array, assign new value to variable in array

In my script I ask the user for some input and save it into some variables. Before using the strings in the variables I want to cut them if they are too long and add an ellipsis at the end.
So I put all of the variables in an array and send them through a loop and an if statement and reasign the new value to the variable in the array. I have tried many ways and none have worked. The following being an example:
preset1="Short string"
preset2="Not long very string"
preset3="A very long string here which we will then cut"
presets=("${preset1}" "${preset2}" "${preset3}")
for x in "${presets[#]}"; do
if [[ "${#x}" -gt 20 ]]; then
y="${x:0:20}..."
presets[$x]="$y"
fi
done
Please help!
You have to loop over indexes of your array in order to change the values:
for x in "${!presets[#]}"; do
str=${presets[$x]}
(( ${#str} > 20 )) && presets[$x]="${str:0:20}..."
done
Works for associative and sparse arrays as well.
For variety, you can also use only parameter expansion like this:
for x in "${!presets[#]}"; do
str=${presets[$x]}
suffix=${str:20}
presets[$x]=${str:0:20}${suffix:+...}
done
You need to use the array[i] syntax to assign to array elements:
for ((i = 0; i < ${#presets[#]}; ++i)); do
x=${presets[i]}
if [[ "${#x}" -gt 20 ]]; then
y="${x:0:20}..."
presets[i]="$y"
fi
done

How can I assign a range using array length?

This is probably a silly question, more out of curiosity. I have an array in bash:
array=(name1.ext name2.ext name3.ext)
I want to strip off the extension from each element. I was trying to do this by looping over each element, but I was having trouble setting the range of the loop (see below):
for i in 'echo {0..'expr ${#array[#]} - 1'}'; do
newarray[$i]+=$(echo "${array[$i]:0:5}");
done
Please note ' = "back-tick" within the code-block because I wasn't sure how to escape it.
I'm not able to just use a set range (e.g. seq 0 3), because it changes based on the folder, so I wanted to be able to use the length of the array minus 1. I was able to work around this using:
for (( i=0; i<${#array[#]}; i++ )); do
newarray[$i]+=$(echo "${array[$i]:0:5}"); done
But I thought there should be some way to do it with the "array length minus 1" method above and wondered how I was thinking about this incorrectly. Any pointers are appreciated.
Thanks!
Dan
You can apply various parameter expansion operators to each element of an array directly, without needing an explicit loop.
$ array=(name1.ext name2.ext name3.ext)
$ printf '%s\n' "${array[#]%.ext}"
name1
name2
name3
$ newarray=( "${array[#]%.ext}" )
In general, though, there is nearly never any need to generate a range numbers to iterate over. Just use the C-style for loop:
for ((i=0; i< ${#array[#]}; i++ )); do
newarray[$i]="${array[i]%.ext}"
done
With Bash, you could simply loop over your array elements with ${files[#]}:
#!/bin/bash
files=(name1.ext name2.ext name3.ext)
for f in ${files[#]}; do
echo "${f%.*}"
done
Also substring removal ${f%.*} is a better choice if you have extensions of different lengths.
You can use the seq command
for i in `seq 0 $(( ${#array[#]} - 1 ))`
do
···
done
or the bash brace expansion (but in this case you need eval):
for i in `eval echo {0..$(( ${#array[#]} - 1 ))}`
do
···
done
But there is another better (it works even in sparse arrays): let's make bash give us the array indexes:
for i in ${!array[#]}
do
···
done

How do i create array and put value on it - BASH script

ahhh array and loops my weakest links. I was trying to create array depending on user input so
printf "%s\n" "how may array you want"
read value
after this i will ask what value user want to put on a array(this is the bit im stuck on)
i=1
while [ $i -le $value ]
do
echo "what value you want to put in array $i"
read number
echo $number >> array.db
i=$(( i+1 ))
echo
done
although this method works(i think) but i'm not too sure if i'm actually creating an array and putting value to that array.
you can expand arrays in bash dynamically. you can use this snippet
a=(); a[${#a[#]}]=${number}; echo ${a[#]}
The first statement defines an empty array. with the second (which you can use in your while loop) you insert a value at last elment position + 1, due to ${#a[#]} represents the length of a. the third statement just prints all elements in the array.

change array value while looping in bash

The code
SourceFolder[0]=""
SourceFolder[1]="inbound2"
SourceFolder[2]="inbound3"
for i in "${!SourceFolder[#]}"
do
if [ -z "${SourceFolder[$i]}"]; then
${SourceFolder[$i]} = "TEST"
fi
done
${SourceFolder[$i]} = "TEST" - doesn't work
it says
=: command not found
How to change value in current loop index in an array?
Because of the first space = is not interpreted as an assignment. There is a full explanation on So.
Btw ${SourceFolder[$i]} evaluate the array element, which is not what you want to do. For instance for the first one it is the empty string.
Replaces with SourceFolder[$i]=
You must change indexnumber in the your array:
ARRAYNAME[indexnumber]=value
ok, you have array is:
array=(one two three)
you can add count to your script for initialize and change element for array indexnumber, example:
#!/bin/bash
count=0
array=(one two three)
for i in ${array[#]}
do
echo "$i"
array[$count]="$i-indexnumber-is-$count"
count=$((count + 1))
echo $count
done
echo ${array[*]}
Result:
bash test-arr.sh
one
1
two
2
three
3
one-indexnumber-is-0 two-indexnumber-is-1 three-indexnumber-is-2

Resources