Assigning to a positional parameter

Freeman picture Freeman · Dec 7, 2012 · Viewed 10.1k times · Source

How can I assign a value to a positional parameter in Bash? I want to assign a value to a default parameter:

if [ -z "$4" ]; then
   4=$3
fi

Indicating that 4 is not a command.

Answer

msw picture msw · Dec 7, 2012

The set built-in is the only way to set positional parameters

$ set -- this is a test
$ echo $1
this
$ echo $4
test

where the -- protects against things that look like options (e.g. -x).

In your case you might want:

if [ -z "$4" ]; then
   set -- "$1" "$2" "$3" "$3"
fi

but it would probably be more clear as

if [ -z "$4" ]; then
   # default the fourth option if it is null
   fourth="$3"
   set -- "$1" "$2" "$3" "$fourth"
fi

you might also want to look at the parameter count $# instead of testing for -z.