在 CentOS(以及大多数 Linux 发行版)中,反引号(
)通常用于命令替换。命令替换允许你将一个命令的输出嵌入到另一个命令或脚本中。这在需要使用一个命令的输出作为另一个命令的参数时非常有用。
以下是一些使用反引号的应用场景:
file_size=`ls -l filename.txt | awk '{print $5}'`
echo "The size of the file is: $file_size bytes"
backup_dir="/home/user/backup-$(date +%Y%m%d)"
mkdir $backup_dir
current_date=`date`
hostname=`hostname`
echo "Today is: $current_date"
echo "The hostname is: $hostname"
需要注意的是,虽然反引号在很多情况下仍然有效,但现代的 shell 脚本更推荐使用 $()
语法进行命令替换,因为它更易读,且可以嵌套使用。例如,上面的示例可以用 $()
重写为:
file_size=$(ls -l filename.txt | awk '{print $5}')
echo "The size of the file is: $file_size bytes"
backup_dir="/home/user/backup-$(date +%Y%m%d)"
mkdir $backup_dir
current_date=$(date)
hostname=$(hostname)
echo "Today is: $current_date"
echo "The hostname is: $hostname"