Reputation: 61
I'm writing a bash script and I am reading in a file with 3 lines each with only 1 number. I have to set each line to a new variable. I'm not quite sure how to do this but this is what I am doing now:
VAR1=0
VAR2=0
VAR3=0
while read line
do
VAR1=$line
VAR2=$line
VAR3=$line
done <$FILE
The result I'm getting is just the last line in the file for all 3 variables. Any help yould be great.
Upvotes: 0
Views: 3349
Reputation: 6058
My personal solution is slightly different and can be used in a pipe.
This works if you know that output will be divided every N lines (2 for this case)
YOUR_COMAND | while read line;
do
((i++))
lines[i]=$line
if [ $i = 2 ]; then
echo "You received new output: ${lines[1]} ${lines[2]}"
#do your stuff with all the lines you gathered
i=0;
fi
done
Upvotes: 0
Reputation: 58351
This might work for you (BASH):
OIFS=$IFS; IFS=$'\n'; var=($(<file)); IFS=$OIFS
for ((n=0;n<${#var[@]};n++)){ echo "\${var[$n]}=${var[n]}"; }
Upvotes: 0
Reputation: 152956
Believe it or not, you can do this using printf
i=0
while read line; do
((i++))
varname="VAR$i"
printf -v $varname "$line"
done < FILE
Source: Creating a string variable name from the value of another string
Upvotes: 2
Reputation: 7092
Nosid's answer does what you want, but if you really needed an array, you can do it like this:
# populate ARRAY
ARRAY=()
while read LINE
do
ARRAY+=("$LINE")
done < test
# subscripting
echo ${ARRAY[0]}
echo ${ARRAY[1]}
echo ${ARRAY[2]}
# looping
for LINE in "${ARRAY[@]}"
do
echo "$LINE"
done
Upvotes: 0