I have a command called "mycommand" which returns a one line data that has 5 columns, like this:
val1 val2 val3 val4 val5
I would like to write a script to assign val1 to a variable and val2 to a different variable.
I have a shell script that does something like this:
INFO=$(mycommand | awk 'NR==1 {print $1,$2}')
echo "INFO 1 is ${INFO[1]}"
echo "INFO 2 is ${INFO[2]}"
Obviously the above one does not work.
Can someone let me know how I can achieve this?
CodePudding user response:
You can create an array using the output of mycommand
, by enclosing the command substitution $(command)
with parentheses ( $(command) )
.
Array indexing also starts at 0, so you'd want to use indexes 0/1.
#!/bin/bash
mycommand()
{
echo val1 val2 val3 val4 val5
}
INFO=( $(mycommand | awk 'NR==1 {print $1,$2}') )
echo "INFO O is ${INFO[0]}"
echo "INFO 1 is ${INFO[1]}"
# Note: you could also just capture the whole output in the array
printf "\nAll columns:\n"
INFO=( $(mycommand) )
for ((i = 0; i < ${#INFO[@]}; i )); do
echo "INFO $i is ${INFO[$i]}"
done
Output
INFO O is val1
INFO 1 is val2
All columns:
INFO 0 is val1
INFO 1 is val2
INFO 2 is val3
INFO 3 is val4
INFO 4 is val5