评估 shell 脚本中的字符串

Joh*_*ino 8 command-line bash scripts

我正在关注这个 bash shell 脚本指南:

在数值比较一节中,它引用了一个例子:

anny > num=`wc -l work.txt`

anny > echo $num
201

anny > if [ "$num" -gt "150" ]
More input> then echo ; echo "you've worked hard enough for today."
More input> echo ; fi
Run Code Online (Sandbox Code Playgroud)

上面似乎发生的是我们将一串命令存储在一个 bash 变量中,然后我们对该变量调用 echo。似乎发生的是评估字符串并执行 wc 命令并将行数返回到控制终端。

好的,所以我在 Ubuntu 12.04 中启动我的终端并尝试类似的操作:

$ touch sample.txt && echo "Hello World" > sample.txt
$ cat sample.txt
Hello World
$ num='wc -l sample.txt'
echo $num
wc -l sample.txt
Run Code Online (Sandbox Code Playgroud)

等一下,它没有计算字符串并返回行数。那只是将字符串回显到终端。为什么我得到了不同的结果?

c0r*_*0rp 5

请注意该符号:

'

单引号

   Enclosing characters in single quotes preserves the  literal  value  of
   each character within the quotes.  A single quote may not occur between
   single quotes, even when preceded by a backslash.
Run Code Online (Sandbox Code Playgroud)

`

反引号

   Command substitution allows the output of a command to replace the com?
   mand name.  There are two forms:

          $(command)
   or
          `command`

   Bash performs the expansion by executing command and replacing the com?
   mand  substitution  with  the  standard output of the command, with any
   trailing newlines deleted.
Run Code Online (Sandbox Code Playgroud)

所以反引号将命令的结果返回到标准输出。这就是为什么

`wc -l sample.txt`
Run Code Online (Sandbox Code Playgroud)

返回命令的结果,而

'wc -l 样本.txt'

只需像往常一样返回“wc -l sample.txt”

考虑这样做作为例子:

$ A='wc -l /proc/mounts'
$ B=`wc -l /proc/mounts`
$ C=$(wc -l /proc/mounts)
Run Code Online (Sandbox Code Playgroud)

现在回显所有三个变量:

$ echo $A
wc -l /proc/mounts
$ echo $B
35 /proc/mounts
$ echo $C
35 /proc/mounts
Run Code Online (Sandbox Code Playgroud)


Dan*_*ela 2

您需要使用反引号来计算表达式。

$ num=`wc -l sample.txt`
$ echo $num
1 sample.txt
Run Code Online (Sandbox Code Playgroud)

如果您只想在输出中看到“1”,请使用命令

$ num=`cat sample.txt | wc -l`
$ echo $num
1
Run Code Online (Sandbox Code Playgroud)

并且也有效:

$ num=`wc -l < sample.txt`
$ echo $num
1
Run Code Online (Sandbox Code Playgroud)

有关其他信息,请参阅命令行上双引号 " "、单引号 ' ' 和反引号 ´ ´ 之间的区别?