Ilikeperl Ilikeperl - 6 months ago 13
Bash Question

Assign Output of Shell Command To Variable

I want to assign output of shell command To variable.

If I directly echo the command, the code will execute correctly

for ((i=0; i<${#result[@]}; i++)); do
echo ${result[$i]} | awk '{print $1}'
done


But, If I assign it to variable

size=`${result[$i]} | awk '{print $1}'`
echo $size


Or

size=$(${result[$i]} | awk '{print $1}')
echo $size


They are not worked.

Can anyone give me some suggestion for addressing it !?

Many Thanks

Yiwei

Answer

You missed the echo

size=$(echo ${result[$i]} | awk '{print $1}')

Here the output the the echo is passed as input to the awk

The $() or back ticks just run the command and assign it to a variable, so when you just write

${result[$i]} | awk '{print $1}'

it won't give you anything as nothing is passed as input to the awk command.