Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning to a positional parameter

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.

like image 559
Freeman Avatar asked Dec 07 '12 11:12

Freeman


1 Answers

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.

like image 126
msw Avatar answered Sep 20 '22 15:09

msw