Multiple command output into variable Bash script

2020-05-09 09:20发布

I reviewed the multiple threads on this and am still having issues, here is the command I'm trying to execute. Commands without the $() print the desired output to the console without issue, I just can't seem to put that value into a variable to be used later on.

MODEL3= $(/usr/sbin/getSystemId | grep "Product Name" | awk '{print $4}')

but

MODEL3= /usr/sbin/getSystemId | grep "Product Name" | awk '{print $4}'  

-will output to the console. Thanks so much!

标签: linux bash shell
2条回答
劳资没心,怎么记你
2楼-- · 2020-05-09 10:08

That is correct:

MODEL3=$(/usr/sbin/getSystemId | grep "Product Name" | awk '{print $4}')

But you can write the same without grep:

MODEL3=$(/usr/sbin/getSystemId | awk '/Product Name/{print $4}')

Now you have the result in the MODEL3 variable and you can use it further as $MODEL3:

echo "$MODEL3"
查看更多
Evening l夕情丶
3楼-- · 2020-05-09 10:24

Spaces Not Legal in Variable Assignments

Variable assignments must not have spaces between the variable name, the assignment operator, and the value. Your current line says:

MODEL3= $(/usr/sbin/getSystemId | grep "Product Name" | awk '{print $4}')

This actually means "run the following expression with an empty environment variable, where MODEL3 is set but empty."

What you want is an actual assignment:

MODEL3=$(/usr/sbin/getSystemId | grep "Product Name" | awk '{print $4}')
查看更多
登录 后发表回答