I have a bash script which seems to lose the value of the readonly constant after the first time thru the for-in loop. For example:
#!/bin/bash
readonly DIR="./groups/"
for output in "${array[@]}"
do
catstring+="$DIR$output "
done
printf "$catstring"
cat $catstring > outputfile
The array has a bunch of names in it like: file1 file2 file3, etc.
The output from the printf statement is "./groups/file1 file2 file3". What I'm expecting is "./groups/file1 ./groups/file2 ./groups/file3".
Why is bash losing the value of $DIR after the first time thru the for-in loop?
"file1 file2 file3"
notfile1 file2 file3
so there is a single (quoted) item to loop over. – DerfK Jul 24 '14 at 18:42declare -A x ; x[0]=a ; x[1]=b ; x[2]="c d" ; for y in "${x[@]}"; do echo $y; done
What happens? – David Tonhofer Jul 24 '14 at 19:49unset x; declare -A x ; x[0]=a ; x[1]=b ; x[2]="c d" ; for y in ${x[@]}; do echo $y; done
erroneously yields 4 lines; Quotedunset x; declare -A x ; x[0]=a ; x[1]=b ; x[2]="c d" ; for y in "${x[@]}"; do echo $y; done
correctly yields three lines. HOWEVER!! If you managed to put all the elements into the FIRST element of the array, one would EXACTLY get your problem. Ah-hah! – David Tonhofer Jul 24 '14 at 20:18mktmp
succeeded though by checking the$?
return value:unset x; declare -A x; i=0; FILE=mktmp ; if [[ $? != 0 ]]; then exit 1; fi; cat /etc/hosts > $FILE ; while read; do x[$i]="$REPLY"; echo "Read $REPLY; i is now $i"; let i=$i+1; done < $FILE; echo "i is $i"; for y in "${x[@]}"; do echo "<$y>"; done
– David Tonhofer Jul 25 '14 at 13:27