如何将 eval 的结果分配给 bash 脚本中的变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10049592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I assign the result of eval to variable in bash script?
提问by jimd
I have a bash script that returns a list, which is what I want, but I need to put the results in a variable so I can operate on them one at a time in a for loop.
我有一个 bash 脚本,它返回一个列表,这正是我想要的,但我需要将结果放入一个变量中,以便我可以在 for 循环中一次对它们进行一个操作。
#!/bin/bash
processID="ps aux | grep `date +"%b"` | gawk '{print $2}'"
eval $processID
How do I assign the result of eval to a variable? Thanks
如何将 eval 的结果分配给变量?谢谢
回答by Alessandro Pezzato
pid=$( ps aux | grep `date +"%b"` | awk '{print }' )
回答by jordanm
You can cut out the need for grep since you are already using awk. The "$" does not need to be escaped because expansions do not occur inside of single quotes.
由于您已经在使用 awk,因此您可以不再需要 grep。"$" 不需要转义,因为扩展不会出现在单引号内。
pid=$(ps aux | awk -vdate=$(date +%b) 'pids=($(ps aux | awk -vdate=$(date +%b) '##代码## ~ date { print }'))
for pid in "${pids[@]}"; do
...
done
~ date { print }')
If you expect multiple pids to be returned, use an array:
如果您希望返回多个 pid,请使用数组:
##代码##
