在bash中,与(反引号)都是用来作命令替换的,命令替换与变量替换差不多,都是用来重组命令行的,先完成引号里的命令行,然后将其结果替换出来,再重组成新的命令行,下面为大家分享一下反引号)和 $()具体使用方法。
反引号的使用方式
下面是一个简单的实例:
[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
Bash 脚本:(反引号)运算符和 $()的使用方式Bash 脚本:(反引号)运算符和 $()的使用方式
$()的使用方式
也可以通过使用$()代替“`反引号来获得相同的结果,如下例所示:
[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/bashwhile truedo
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
Bash 脚本:(反引号)运算符和 $()的使用方式Bash 脚本:(反引号)运算符和 $()的使用方式
如何选择使用哪种方式
这里更推荐使用$()方式。下面是原因: \1. 如果内部命令也使用,运算符可能会变得混乱。
将需要转义内部的“`,如果将单引号作为命令的一部分或结果的一部分,阅读和排除脚本故障可能会变得困难。 如果开始考虑在其他 运算符中嵌套运算符,则事情将不会按预期工作或根本不起作用。
\2. $()操作符更安全,更可预测。
在 $() 运算符中的内容被视为 shell 脚本。从语法上讲,这和把代码保存在文本文件中是一样的。
以下是“`和$()行为差异的一些示例:
[root@localhost ~]# echo '\$x'
\$x
[root@localhost ~]# echo `echo '\$x'`$x
[root@localhost ~]# echo $(echo '\$x')
\$x Bash 脚本:(反引号)运算符和 $()的使用方式Bash 脚本:(反引号)运算符和 $()的使用方式
总结
在较为复杂的命令语句中,推荐使用$()方式。
文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/223449.html<

