Assigning to a positional parameter [duplicate]

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.

Leave a Comment