在Linux中,反引號()是一種命令替換的方式。當你在Shell腳本或命令行中使用反引號時,Shell會執行其中的命令,并將輸出替換到原來的位置。這種方式在現代Shell腳本中已經逐漸被
$(…)語法所取代,因為
$(…)`更易讀且可以嵌套使用。不過,了解反引號仍然有助于理解一些舊的腳本。
以下是一些常見的可以使用反引號執行的命令:
date
:顯示當前日期和時間。
echo "Today is $(date)"
hostname
:顯示主機名。
echo "This is $(hostname)"
whoami
:顯示當前用戶名。
echo "Hello, $(whoami)"
ls
:列出目錄內容。
echo "Files in the current directory: $(ls)"
pwd
:顯示當前工作目錄。
echo "Current directory: $(pwd)"
df
:顯示磁盤空間使用情況。
echo "Disk space usage: $(df -h)"
free
:顯示內存使用情況。
echo "Memory usage: $(free -h)"
uptime
:顯示系統運行時間。
echo "System uptime: $(uptime)"
cut
:從文本行中提取指定部分。
echo "First field of the current directory: $(ls | cut -d' ' -f1)"
grep
:在文本中搜索指定模式。
echo "Files containing 'example': $(ls | grep 'example')"
請注意,為了避免混淆和錯誤,建議使用$(...)
語法而不是反引號。例如,上面的例子可以改寫為:
echo "Today is $(date)"
echo "This is $(hostname)"
echo "Hello, $(whoami)"
echo "Files in the current directory: $(ls)"
echo "Current directory: $(pwd)"
echo "Disk space usage: $(df -h)"
echo "Memory usage: $(free -h)"
echo "System uptime: $(uptime)"
echo "First field of the current directory: $(ls | cut -d' ' -f1)"
echo "Files containing 'example': $(ls | grep 'example')"