heredocument 中带有空参数的 Shell 行为差异

问题描述 投票:0回答:1

Ash、Dash 或 Bash,Zsh 以不同方式处理此处文档中无效的空参数

${var:?}
扩展错误。

这里是使用正版POSIX语法的

experiment.sh
代码:

#!/usr/bin/env sh

empty_var=

read -r value << EOF
Expected fail here ${empty_var:?}"
EOF
printf '$?=%d\nvalue=%s\n' $? "$value"

这里是使用不同 shell 运行实验的代码:

for sh in ash bash dash ksh zsh; do
  printf 'Testing with: %s\n' "$sh"
  LC_ALL=C "$sh" ./experiment.sh || :
  echo
done

得到的结果:

Testing with: ash
./experiment.sh: 5: empty_var: parameter not set or null
$?=2
value=

Testing with: bash
./experiment.sh: line 5: empty_var: parameter null or not set

Testing with: dash
./experiment.sh: 5: empty_var: parameter not set or null
$?=2
value=

Testing with: ksh
./experiment.sh[5]: empty_var: parameter null
$?=1
value=

Testing with: zsh
./experiment.sh:5: empty_var: parameter not set

Bash 和 Zsh 立即停止执行,而其他 shell 继续执行,只是提高返回码

$?
.

对于这种与真正的 POSIX 语法结构的行为差异,有什么解释?

是否记录了为什么 Bash 或 Zsh 选择退出脚本而不是像 Ksh、Dash 或 Ash 那样返回失败代码?

请注意,在其他上下文中,例如在字符串中展开,所有 shell 都会退出脚本。

据我所知,行为差异仅发生在此处的文档中。

bash shell posix ksh behavior
1个回答
0
投票

对于 bash,它被记录在案

here

${parameter:?word}

If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

here
是 zsh 文档。

© www.soinside.com 2019 - 2024. All rights reserved.