在 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"