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。私はこれを見つけましたが、これが単一の場所パラメータを変更する正しい方法であるかどうかはわかりません。

おすすめ記事