← 中文资源

简体中文版本

Bash 命令替换的常见用法

演示用 $() 捕获命令输出、嵌套替换、拼接字符串、配合算术与条件判断,并用 mapfile 把多行输出读入数组。

阅读英文原文

功能说明

脚本展示命令替换的多种写法:把 date、wc、hostname、whoami 等命令的标准输出保存到变量,嵌套 dirname 计算上级目录,在字符串中拼接替换结果,配合算术表达式换算文件大小,并在条件与数组读取中使用替换结果。

关键代码

  • current_date=$(date +%Y-%m-%d) 捕获输出并赋给变量;$() 比反引号更易读,也支持嵌套。
  • grandparent=$(dirname "$(dirname "$(pwd)")") 演示多层嵌套,内层先执行。
  • size=$(stat -c%s /etc/hostname 2>/dev/null || echo 0) 在替换内部提供默认值,避免文件缺失时报错。
  • output=$(grep "localhost" /etc/hosts 2>/dev/null) || true 后立即取 $?,用于区分“找到”和“未找到”。
  • mapfile -t conf_files < <(find /etc -maxdepth 1 -name "*.conf" 2>/dev/null) 用进程替换把多行结果读入数组,-t 去掉行尾换行。

使用注意

命令替换会去掉输出末尾的换行符,且未加引号时结果会按空白分词,路径含空格时应写成 "$(command)"。赋值语句本身的退出状态就是替换命令的状态,但若后面还有其他命令,$? 会被覆盖,因此脚本先保存状态再判断。在 set -e 下,替换命令失败可能导致脚本退出,需要显式处理。

验证方式

保存为 command-substitution.sh 并执行,检查日期格式为 YYYY-MM-DD、/etc 文件计数为正数、当前用户与主机名拼接正确,mapfile 统计到的配置文件数量与 find 手动执行结果一致。

代码示例

#!/usr/bin/env bash
set -euo pipefail

# Basic command substitution
current_date=$(date +%Y-%m-%d)
echo "Date: $current_date"

# Preferred $() syntax over backticks
files_count=$(ls -1 /etc 2>/dev/null | wc -l)
echo "Files in /etc: $files_count"

# Nested command substitution
grandparent=$(dirname "$(dirname "$(pwd)")")
echo "Grandparent dir: $grandparent"

# Substitution in strings
host=$(hostname)
user=$(whoami)
echo "${user}@${host}:$(pwd)"

# Substitution with arithmetic
size=$(stat -c%s /etc/hostname 2>/dev/null || echo 0)
echo "Hostname file size: $size bytes"
echo "KB: $(( size / 1024 )) KB"

# Substitution in conditionals
if [[ $(id -u) -eq 0 ]]; then
    echo "Running as root"
else
    echo "Running as $(whoami)"
fi

# Capture exit status separately
output=$(grep "localhost" /etc/hosts 2>/dev/null) || true
status=$?
if (( status == 0 )); then
    echo "Found: $output"
elif (( status == 1 )); then
    echo "Not found"
fi

# Array from command output
mapfile -t conf_files < <(find /etc -maxdepth 1 -name "*.conf" 2>/dev/null)
echo "Config files found: ${#conf_files[@]}"