Appearance
命令替换
命令替换(Command Substitution)允许将命令的输出结果赋值给变量或嵌入到其他命令中。
两种语法
bash
# 推荐写法(支持嵌套)
$(命令)
# 旧式写法(不支持嵌套)
`命令`基本用法
bash
# 获取当前日期
today=$(date +%Y-%m-%d)
echo "今天是:$today"
# 获取当前用户
current_user=$(whoami)
echo "当前用户:$current_user"
# 获取目录文件数量
file_count=$(ls /etc | wc -l)
echo "/etc 下有 $file_count 个文件"
# 获取主机名
hostname=$(hostname)
echo "主机名:$hostname"直接嵌入命令
bash
# 在字符串中直接嵌入
echo "当前时间:$(date +'%H:%M:%S')"
echo "家目录:$HOME,当前路径:$(pwd)"
# 在参数中使用
mkdir "backup_$(date +%Y%m%d)"
cp file.txt "file_$(date +%Y%m%d_%H%M%S).bak"嵌套命令替换
bash
# 嵌套(只能用 $() 形式)
result=$(echo $(echo "hello world") | tr 'a-z' 'A-Z')
echo "$result" # HELLO WORLD
# 获取脚本所在目录的绝对路径
script_dir=$(dirname $(readlink -f $0))捕获多行输出
bash
# 获取多行输出(默认会压缩换行)
files=$(ls /etc/*.conf)
echo "$files" # 使用双引号保留换行
# 遍历命令输出的每一行
while IFS= read -r line; do
echo "处理:$line"
done < <(ls /var/log)
# 或者
for line in $(cat /etc/hosts); do
echo "$line"
done处理命令输出
bash
#!/bin/bash
# 获取进程 PID
pid=$(pgrep nginx)
if [ -n "$pid" ]; then
echo "nginx 运行中,PID: $pid"
fi
# 获取文件行数
lines=$(wc -l < /etc/passwd)
echo "/etc/passwd 有 $lines 行"
# 获取磁盘使用率
usage=$(df / | awk 'NR==2 {print $5}' | tr -d '%')
if [ "$usage" -gt 80 ]; then
echo "磁盘使用率超过 80%!当前:${usage}%"
fi
# 获取 IP 地址
ip=$(hostname -I | awk '{print $1}')
echo "本机 IP:$ip"在条件判断中使用
bash
#!/bin/bash
# 判断命令输出是否为空
if [ -z "$(pgrep apache2)" ]; then
echo "apache2 未运行"
fi
# 判断输出是否包含特定内容
if echo "$(uname -s)" | grep -q "Linux"; then
echo "当前系统是 Linux"
fi算术运算结合
bash
# 获取系统内存(MB)
total_mem=$(free -m | awk 'NR==2 {print $2}')
used_mem=$(free -m | awk 'NR==2 {print $3}')
free_mem=$((total_mem - used_mem))
echo "空闲内存:${free_mem} MB"注意事项
bash
# 包含空格的输出要用双引号包裹
file_list="$(ls -la)"
echo "$file_list" # 正确:保留格式
# 不加引号会丢失换行和多余空格
echo $file_list # 可能显示混乱
# 命令替换会去掉末尾换行
result=$(printf "hello\n\n")
echo "${#result}" # 5(末尾换行被去掉)