3

I want to assign the output of a shell command to a 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 a variable,

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

Or

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

They are not working.

How can I fix it?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
ITnewbie
  • 173
  • 2
  • 9
  • While this is more or less a typo error, the canonical is *[How do I set a variable to the output of a command in Bash?](https://stackoverflow.com/questions/4651437)*. Despite the unspecific title, it covers the case of ***(variable) input to the external command*** (in a (Bash) variable. – Peter Mortensen Nov 10 '20 at 02:06

1 Answers1

6

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.

nu11p01n73R
  • 24,873
  • 2
  • 34
  • 48