如何替换这个 Zsh 表达式中的变量?

How to substitute variable in this Zsh expression?

我需要在这个表达式中替换变量 x

my-func() {
  x="Hello world"
  y=${1:?Missing argument, use $x}
  echo -- $y
}

它在缺少第一个函数的参数而不是“Hello world”时打印 $x。如何替换此错误消息中的变量?有可能吗?

使用'zsh','${var:?work) 中的单词不会被插入,而是打印as-is。很可能是一个错误,因为 bash、破折号、ksh 和其他将遵循 POSIX 标准:来自 https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02

${parameter:?[word]} Indicate Error if Null or Unset. If parameter is unset or null, the expansion of word (or a message indicating it is unset if word is omitted) shall be written to standard error and the shell exits with a non-zero exit status. Otherwise, the value of parameter shall be substituted. An interactive shell need not exit.

另一种解决方案是进行显式检查:

my-func() {
  x="Hello world"
#  y=${1:?Missing argument, use $x}
  if [ ! " ] ; then
      echo "$funcstack[1]: $LINENO: $1: missing argument use $x" >&2
      exit 1
  fi
  y=
  echo -- $y
}

可以通过将 'exit' 替换为 'throw'(需要自动加载)来编写更漂亮的代码。