输出awk命令结果变量


output awk command result to variable

我从控制台运行以下命令,它输出正确的结果:0

1
sudo -H -u hadoop bash -c"/home/hadoop/hadoop-install/bin/hadoop dfsadmin -report | grep 'Under replicated blocks' | awk '{print \$4}'"

但是,如果我把它放在shell脚本中并将其分配给一个变量,"awk"将不再工作,它只输出"grep"的整个结果:

1
2
replications=`sudo -H -u hadoop bash -c"/home/hadoop/hadoop-install/bin/hadoop dfsadmin -report | grep 'Under replicated blocks' | awk '{print \$4}'"`
echo"Replications: $replications"

结果:Replications: Under replicated blocks: 0。如何使awk再次工作,只输出第4列,即0而不是整个字符串?


在倒勾命令替换中,\后接$只表示$。从POSIX标准:

Within the backquoted style of command substitution, backslash shall retain its literal meaning, except when followed by: '$', '`', or '\' (dollar sign, backquote, backslash). (...)

With the $(command) form, all characters following the open parenthesis to the matching closing parenthesis constitute the command. Any valid shell script can be used for command, except a script consisting solely of redirections which produces unspecified results.

更明确地说,从bash手册页:

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

所以最简单的方法是

1
replications=$(sudo -H -u hadoop bash -c"/home/hadoop/hadoop-install/bin/hadoop dfsadmin -report | grep 'Under replicated blocks' | awk '{print \$4}'")

但是

1
replications=`sudo -H -u hadoop bash -c"/home/hadoop/hadoop-install/bin/hadoop dfsadmin -report | grep 'Under replicated blocks' | awk '{print \\\$4}'"`

也可以工作。