代码 Bash 5.3 的两种不 fork 命令替换:${ cmd; } 与 ${| cmd; }

2026-11-23 21:05:07

Bash 5.3 的两种不 fork 命令替换:${ cmd; } 与 ${| cmd; }

2025-07-05,Chet Ramey 发布 GNU Bash 5.3。官方 NEWS 里最核心的一条写的是:

"s. New form of command substitution: ${ command; } or ${|command;} to capture the output of COMMAND without forking a child process and using pipes."

发布公告的表述是:

"There is a new form of command substitution that executes the command in the current shell execution context. Two forms are implemented: one that reads the command substitution's output and another that expects to find the result in the REPLY shell variable when the command substitution completes."

项目地址:

两种形式

  • ${ command; }:把命令的输出作为替换结果,不 fork 子进程、不使用管道。
  • ${| command; }:在当前 shell 执行命令,命令完成时从 REPLY 变量取结果。

关键在于“不 fork”。命令运行在当前 shell 的执行上下文里,cd、变量赋值这类副作用会留在当前 shell;而 $(...) 在子 shell 中执行,副作用随子 shell 一起消失。这是两种语法的根本差别。

示例:副作用留在哪一边

先看 count 依次经过两种替换后的结果:

count=0

res=${| count=$((count+1)); REPLY=$count; }
echo "$count $res $REPLY"     # 1 1 1

res2=$( count=$((count+1)); echo "$count" )
echo "$count $res2"           # 1 2

第一次用 ${| ...; },count 在当前 shell 里从 0 变成 1,REPLY=1 也留在当前 shell,替换结果就是 REPLY 的值 1。第二次用 $( ... ),子 shell 里把 count 加到了 2 并 echo 出来,命令替换的返回值是 2,但父 shell 的 count 仍是 1——子 shell 的改动没有回来。

${ command; } 同理,输出被捕获成词,副作用留在当前 shell:

cd /tmp
out=${ cd /; pwd; }
echo "$out"   # /
pwd           # /     —— cd 生效在当前 shell

换成 $( ... ):

cd /tmp
out=$(cd /; pwd)
echo "$out"   # /
pwd           # /tmp  —— cd 只发生在子 shell

其他新特性(NEWS 摘录)

版本相关的行为细节(默认值、边界情况)以本机 bash --version 显示的版本和实测为准。

  • GLOBSORT:控制路径名展开结果的排序,可取 name、size、blocks、mtime、atime、ctime、numeric、none,并支持升序/降序。
  • compgen -V varname:结果存入变量而不是写到 stdout。
  • read -E:用 readline 读取,带默认的 bash 补全(包括可编程补全)。
  • source / . 的 -p PATH:用给定的 PATH 而不是 $PATH 搜索文件。
  • BASH_MONOSECONDS:动态变量,返回系统单调时钟值。
  • BASH_TRAPSIG:trap 执行期间设为该信号编号。
  • trap -P:打印每个信号参数关联的 trap 动作。
  • [[ ]] 里正则编译失败时打印错误信息。
  • 未闭合复合命令报错时给出起始行号。
  • $TIMEFORMAT 精度从 3 位扩到 6 位。
  • MULTIPLE_COPROCS 默认开启。
  • $PATH 为 NULL 时等同 .。
  • 可用不同默认值编译 patsub_replacement。
  • complete / compopt 新增 fullquote。
  • bash_source_fullpath shopt:BASH_SOURCE 放完整路径。
  • shell 名为 su / -su 时 $BASH 使用登录 shell 路径。
  • 新增可加载内建 fltexpr(浮点,类似 let)、kv、strptime。
  • 新的 readline 可绑定命令 bash-vi-complete;M-x 默认绑定 execute-named-command。
  • 源码改为 C23 一致性,不再能用 K&R 风格 C 编译器编译;Readline 8.3 同时发布,链接只支持 readline-8.1+。

不兼容变更

  • test 内建在带括号子表达式且参数超过 4 个时,解析行为有变化(与 coreutils 对齐),这类表达式本身仍有歧义。
  • 交互式 shell 在 source 脚本期间不再提示已完成作业,推迟到脚本结束。
  • jobs 内建运行后按 POSIX 把作业从作业表移除。
  • 交互式 shell 的作业提示在 trap 运行期间也会打印。

上手前先跑 bash --version 确认版本,再拿上面的 count 例子复现一遍,两种替换的差异就很直观了。

复制全文 生成海报 Shell Bash 脚本

推荐文章

程序员茄子在线接单