Shell Daily 2025-12-20: Here Strings (<<<)

Shell Daily 2025-12-20: Here Strings (<<<)

你是否经常写出这样的代码:为了把一个变量的值传给 grepsed 处理,不得不专门在前面加一个 echo 和管道符?

# 略显笨重的写法
echo "$ERROR_MSG" | grep -q "Timeout"

这种写法虽然没问题,但总觉得为了传个字符串特意开一个管道(Pipe)有点“杀鸡用牛刀”。Shell 其实提供了一种更精简、更高效的语法来处理单行文本输入——Here Strings

怎么用

语法是三个小于号:command <<< "string"

它把右边的字符串(或变量内容)通过标准输入(stdin)喂给左边的命令。

  • Bash / Zsh: 原生支持,非常推荐。
  • POSIX sh: 不支持(POSIX 标准只支持 << Here Document)。

适用场景

任何需要处理短文本流,且不想使用管道的场景。特别是当你需要把变量内容传给 bc (计算器)、sedgrepjson 解析工具时。

示例 1:极简计算器

做浮点运算时,我们常调用 bc。用管道写显得很长,用 Here String 就紧凑得多:

# 计算磁盘使用率百分比
# 这里的 scale=2 是 bc 的参数,指定保留两位小数
ratio=$(bc -l <<< "scale=2; $used_space / $total_space * 100")

示例 2:避免子 Shell 陷阱 (关键技巧)

这是 Here String 最大的隐藏价值。当你用管道 echo "data" | read var 时,Bash 会把 read 放在子 Shell 中运行,导致变量赋值在下一行就失效了。而使用 <<<read 是在当前 Shell 执行的。

info="10.0.0.5  nginx-master"

# 错误写法:管道会创建子 Shell,ip 和 name 读完就丢了
echo "$info" | read ip name
# echo $ip -> 输出为空

# 正确写法:变量成功赋值
read ip name <<< "$info"
echo "IP is $ip, Name is $name"

示例 3:快速检查变量内容

在脚本中做字符串匹配,不想写复杂的 [[ $str =~ regex ]] 正则语法时,可以直接丢给 grep

log_line="Error: Connection refused at 12:00"

# 如果日志行里包含 "Error",则发送报警
if grep -q "Error" <<< "$log_line"; then
    send_alert "Something went wrong!"
fi
posted @ 2025-12-20 14:10  Terrasse  阅读(2)  评论(0)    收藏  举报