3

Inside my bash script:

This works:

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

But, if I replace it with:

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

I get the following error

line #: 1ドル: cannot assign in this way

Why I can't assign to ${1}?

Jeff Schaller
68.8k35 gold badges122 silver badges263 bronze badges
asked Jan 12, 2019 at 11:59

1 Answer 1

4

From bash's manpage:

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).

and later, under Parameter Expansion

${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.

If you want to assign a default value to the positional parameter 1ドル like in your question, you can use

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

Here I've used a combination of shift and set. I've just come up with this and I'm not sure if it's the proper way to change a single positional parameter.

answered Jan 12, 2019 at 12:13
4
  • 1
    Additionally, to assign something to 1ドル, you would use e.g. set -- "$PWD" (this would clear the other positional parameters though, unless you did set -- "$PWD" "$@", which would "push" $PWD to the front of $@). Commented Jan 12, 2019 at 12:55
  • @Kusalananda: I wonder if you can change a single pos. parameter. I've now tried a combination of set and shift, see my edit. Commented Jan 12, 2019 at 13:04
  • Oh, and I probably forgot the --, just in case some of the arguments start with a hyphen. Thanks @Kusalananda Commented Jan 12, 2019 at 13:06
  • Simplified: if [ -z "1ドル" ]; then shift; set -- default "$@"; fi; CWD="1ドル" Commented Jan 12, 2019 at 13:21

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.