简体   繁体   English

将命令的输出分配给变量(BASH)

[英]Assigning output of a command to a variable(BASH)

I need to assign the output of a command to a variable. 我需要将命令的输出分配给变量。 The command I tried is: 我试过的命令是:

grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}'

I try this code to assign a variable: 我尝试使用此代码来分配变量:

UUID=$(grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}')

However, it gives a syntax error. 但是,它会产生语法错误。 In addition I want it to work in a bash script. 另外我希望它在bash脚本中工作。

The error is: 错误是:

./upload.sh: line 12: syntax error near unexpected token ENE=$( grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}'
 )'

./upload.sh: line 12:   ENE=$( grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}'
 )'

well, using the '$()' subshell operator is a common way to get the output of a bash command. 好吧,使用'$()'子shell运算符是获取bash命令输出的常用方法。 As it spans a subshell it is not that efficient. 因为它跨越子壳,所以效率不高。

I tried : 我试过了 :

UUID=$(grep UUID /etc/fstab|awk '/ext4/ {print $1}'|awk '{print substr($0,6)}')
echo $UUID # writes e577b87e-2fec-893b-c237-6a14aeb5b390

it works perfectly :) 它完美地工作:)

EDIT: 编辑:

Of course you can shorten your command : 当然你可以缩短你的命令:

# First step : Only one awk
UUID=$(grep UUID /etc/fstab|awk '/ext4/ {print substr($1,6)}')

Once more time : 再来一次:

# Second step : awk has a powerful regular expression engine ^^
UUID=$(cat /etc/fstab|awk '/UUID.*ext4/ {print substr($1,6)}')

You can also use awk with a file argument :: 您还可以将awk与文件参数一起使用::

# Third step : awk use fstab directlty
UUID=$(awk '/UUID.*ext4/ {print substr($1,6)}' /etc/fstab)

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", eg, 只是出于解决问题的目的,还有别的东西可以尝试看看你是否可以使用它,你也可以尝试使用“反引号”,例如,

cur_dir=`pwd`

would save the output of the pwd command in your variable cur_dir, though using $() approach is generally preferable. pwd命令的输出保存在变量cur_dir中,尽管通常使用$()方法。

To quote from 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. 第二种形式`COMMAND` (使用反引号)对于Bash来说或多或少已经过时,因为它在嵌套方面存在一些问题(“内部”反引号需要被转义)和转义字符。 Use $(COMMAND) , it's also POSIX! 使用$(COMMAND) ,它也是POSIX!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM