共计 1359 个字符,预计需要花费 4 分钟才能阅读完成。
导读 | ` 反引号操作符可以在 shell 脚本中使用,因为它很容易与其他命令结合使用。但是,还有一种更“推荐”的方式来做同样的事情,使用 $()运算符。本文将介绍在 shell 脚本中使用他们的优缺点。 |
反引号的使用方式
下面是一个简单的实例:
[root@localhost ~]# echo "There are `ls | wc -l` files in this directory" | |
There are 10 files in this directory |
ls |wc -l
用于列出和计算当前目录的文件数,然后将它嵌入到 echo 命令中。
在 shell 脚本中,当然可以执行相同的操作,将 ls | wc -l
命令的结果分配给一个变量,稍后使用该变量。
[root@localhost ~]# file_count=`ls | wc -l` | |
[root@localhost ~]# echo "There are $file_count files in this directory" | |
There are 10 files in this directory |
$()的使用方式
也可以通过使用 $()
代替 `
反引号来获得相同的结果,如下例所示:
[root@localhost ~]# echo "There are $(ls | wc -l) files in this directory" | |
There are 10 files in this directory |
下面是一个例子,我需要对网络连接中的某些问题进行故障排除,因此我决定每分钟显示总连接数和等待连接数。
[root@localhost ~]# vim netinfo.sh | |
#!/bin/bash | |
while true | |
do | |
ss -an > netinfo.txt | |
connections_total=$(cat netinfo.txt | wc -l) | |
connections_waiting=$(grep WAIT netinfo.txt | wc -l) | |
printf "$(date +%R) - Total=%6d Waiting=%6d\n" $connections_total $connections_waiting | |
sleep 60 | |
done |
运行一下脚本:
[root@localhost ~]# ./netinfo.sh | |
17:13 - Total= 158 Waiting= 4 | |
17:14 - Total= 162 Waiting= 0 | |
17:15 - Total= 155 Waiting= 0 | |
17:16 - Total= 155 Waiting= 0 | |
17:17 - Total= 155 Waiting= 0 |
如何选择使用哪种方式
这里更推荐使用 $()方式。下面是原因:
1. 如果内部命令也使用 `
,`
运算符可能会变得混乱。
- 将需要转义内部的
`
,如果将单引号作为命令的一部分或结果的一部分,阅读和排除脚本故障可能会变得困难。 - 如果开始考虑在其他
`
运算符中嵌套`
运算符,则事情将不会按预期工作或根本不起作用。
2. $()
操作符更安全,更可预测。
在 $()
运算符中的内容被视为 shell 脚本。从语法上讲,这和把代码保存在文本文件中是一样的。
以下是 `
和 $()
行为差异的一些示例:
[root@localhost ~]# echo '\$x' | |
\$x | |
[root@localhost ~]# echo `echo '\$x'` | |
$x | |
[root@localhost ~]# echo $(echo '\$x') | |
\$x |
总结
在较为复杂的命令语句中,推荐使用 $()方式。
正文完
星哥玩云-微信公众号
