0

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}?

3

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.

  • 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 $@). – Kusalananda Jan 12 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. – Stefan Hamcke Jan 12 at 13:04
  • Oh, and I probably forgot the --, just in case some of the arguments start with a hyphen. Thanks @Kusalananda – Stefan Hamcke Jan 12 at 13:06
  • Simplified: if [ -z "$1" ]; then shift; set -- default "$@"; fi; CWD="$1" – Kusalananda Jan 12 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.