Bash:为变量分配默认值时出错

Bash:为变量分配默认值时出错

在我的 bash 脚本中:

这有效:

CWD="${1:-${PWD}}"

但是,如果我将其替换为:

CWD="${1:=${PWD}}"

我收到以下错误

line #: $1: cannot assign in this way

为什么我不能分配给${1}?

答案1

来自 bash 的联机帮助页:

Positional Parameters
    A  positional  parameter  is a parameter denoted by one or more digits,
    other than the single digit 0.  Positional parameters are assigned from
    the  shell's  arguments when it is invoked, and may be reassigned using
    the set builtin command.  Positional parameters may not be assigned  to
    with  assignment statements.  The positional parameters are temporarily
    replaced when a shell function is executed (see FUNCTIONS below).

后来,在参数扩展

${parameter:=word}
       Assign  Default  Values.   If  parameter  is  unset or null, the
       expansion of word is assigned to parameter.  The value of param‐
       eter  is  then  substituted.   Positional parameters and special
       parameters may not be assigned to in this way.

$1如果您想像问题中那样为位置参数分配默认值,您可以使用

if [ -n "$1" ]
then
  CWD="$1"
else
  shift 1
  set -- default "$@"
  CWD=default
fi

shift在这里我使用了和的组合set。我刚刚想出这个,我不确定这是否是更改单个位置参数的正确方法。

相关内容