Ilikeperl Ilikeperl - 1 year ago 73
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}'

But, If I assign it to variable

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


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

They are not worked.

Can anyone give me some suggestion for addressing it !?

Many Thanks


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download