将命令的输出分配给变量(BASH)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/11527899/
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
Assigning output of a command to a variable(BASH)
提问by Eray Tuncer
I need to assign the output of a command to a variable. The command I tried is:
我需要将命令的输出分配给一个变量。我试过的命令是:
grep UUID fstab | awk '/ext4/ {print }' | awk '{print substr(UUID=$(grep UUID fstab | awk '/ext4/ {print }' | awk '{print substr(./upload.sh: line 12: syntax error near unexpected token ENE=$( grep UUID fstab | awk '/ext4/ {print }' | awk '{print substr(UUID=$(grep UUID /etc/fstab|awk '/ext4/ {print }'|awk '{print substr(# First step : Only one awk
UUID=$(grep UUID /etc/fstab|awk '/ext4/ {print substr(,6)}')
,6)}')
echo $UUID # writes e577b87e-2fec-893b-c237-6a14aeb5b390
,6)}'
 )'
./upload.sh: line 12:   ENE=$( grep UUID fstab | awk '/ext4/ {print }' | awk '{print substr(# Second step : awk has a powerful regular expression engine ^^
UUID=$(cat /etc/fstab|awk '/UUID.*ext4/ {print substr(,6)}')
,6)}'
 )'
,6)}')
,6)}'
I try this code to assign a variable:
我尝试使用此代码分配变量:
# Third step : awk use fstab directlty
UUID=$(awk '/UUID.*ext4/ {print substr(,6)}' /etc/fstab)
However, it gives a syntax error. In addition I want it to work in a bash script.
但是,它给出了语法错误。此外,我希望它在 bash 脚本中工作。
The error is:
错误是:
cur_dir=`pwd`
回答by neuro
well, using the '$()' subshell operator is a common way to get the output of a bash command. As it spans a subshell it is not that efficient.
好吧,使用“$()”子shell 运算符是获取bash 命令输出的常用方法。由于它跨越一个子外壳,因此效率不高。
I tried :
我试过 :
##代码##it works perfectly :)
它完美地工作:)
EDIT:
编辑:
Of course you can shorten your command :
当然,您可以缩短命令:
##代码##Once more time :
再一次:
##代码##You can also use awk with a file argument ::
您还可以将 awk 与文件参数一起使用 ::
##代码##回答by Levon
Just for trouble-shooting purposes, and something else to try to see if you can get this to work, you could also try to use "backticks", e.g,
仅出于故障排除目的,以及其他尝试查看是否可以使其正常工作的目的,您还可以尝试使用“反引号”,例如,
##代码##would save the output of the pwdcommand in your variable cur_dir, though using $()approach is generally preferable.
会将pwd命令的输出保存在变量 cur_dir 中,尽管使用$()方法通常更可取。
To quotefrom a pages given to me on http://unix.stackexchange.com:
要引用从给我一个网页http://unix.stackexchange.com:
The second form
`COMMAND`(using backticks) is more or less obsolete for Bash, since it has some trouble with nesting ("inner" backticks need to be escaped) and escaping characters. Use$(COMMAND), it's also POSIX!
第二种形式
`COMMAND`(使用反引号)对于 Bash 或多或少已经过时了,因为它在嵌套(“内部”反引号需要转义)和转义字符方面存在一些问题。使用$(COMMAND),也是POSIX!

