无法将嵌套命令的输出分配给 bash 中的变量

pra*_*ado 4 bash shell-script variable

我试图将下面的命令(从文件中选择随机行)分配给一个变量,但不起作用。

givinv@87-109:~$ head -$((${RANDOM} % `wc -l < file` + 1)) file | tail -1
cower
givinv@87-109:~$
Run Code Online (Sandbox Code Playgroud)

在我尝试将其分配给变量时遇到的错误下方。

givinv@87-109:~$ VARIA=`head -$((${RANDOM} % `wc -l < file` + 1)) file | tail -1`
bash: command substitution: line 1: unexpected EOF while looking for matching `)'
bash: command substitution: line 2: syntax error: unexpected end of file
bash: command substitution: line 1: syntax error near unexpected token `)'
bash: command substitution: line 1: ` + 1)) file | tail -1'
-l: command not found
givinv@87-109:~$
Run Code Online (Sandbox Code Playgroud)

我什至尝试过同样的 for 循环但不工作::

givinv@87-109:~$ for i in `head -$((${RANDOM} % `wc -l < file` + 1)) file | tail -1`;do echo $i ;done
bash: syntax error near unexpected token `<'
givinv@87-109:~$ 
Run Code Online (Sandbox Code Playgroud)

ter*_*don 15

它不起作用,因为您试图嵌套未转义的反引号:

VARIA=`head -$((${RANDOM} % `wc -l < file` + 1)) file | tail -1`
Run Code Online (Sandbox Code Playgroud)

这实际上首先尝试head -$((${RANDOM} %作为单个命令运行,这会给您第 2 个错误:

$ VARIA=`head -$((${RANDOM} % `
bash: command substitution: line 1: unexpected EOF while looking for matching `)'
bash: command substitution: line 2: syntax error: unexpected end of file
Run Code Online (Sandbox Code Playgroud)

然后,它尝试运行

wc -l < file` + 1)) file | tail -1`
Run Code Online (Sandbox Code Playgroud)

这意味着它尝试评估+ 1)) file | tail -1(在反引号之间),这会给你下一个错误:

$ wc -l < file` + 1)) file | tail -1`
bash: command substitution: line 1: syntax error near unexpected token `)'
bash: command substitution: line 1: ` + 1)) file | tail -1'
Run Code Online (Sandbox Code Playgroud)

您可以通过转义反引号来解决此问题:

VARIA=`head -$((${RANDOM} % \`wc -l < file\` + 1)) file | tail -1`
Run Code Online (Sandbox Code Playgroud)

但是,作为一般规则,通常最好根本不使用反引号。你应该几乎总是使用$()代替。它更健壮,可以使用更简单的语法无限嵌套:

VARIA=$(head -$((${RANDOM} % $(wc -l < file) + 1)) file | tail -1)
Run Code Online (Sandbox Code Playgroud)