反引号操作符可以在 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/bashwhile truedoss -an > netinfo.txtconnections_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_waitingsleep 60done
运行一下脚本:
[root@localhost ~]# ./netinfo.sh17:13 - Total= 158 Waiting= 417:14 - Total= 162 Waiting= 017:15 - Total= 155 Waiting= 017:16 - Total= 155 Waiting= 017: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
总结
在较为复杂的命令语句中,推荐使用$()方式。
本文原创地址:https://www.linuxprobe.com/bash-backtick-usage.html编辑:逄增宝,审核员:逄增宝
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.