• Uncategorized

About bash : Assigning-to-a-positional-parameter

Question Detail

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

Indicating that 4 is not a command.

Question Answer

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

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

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"

but it would probably be more clear as

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

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

You can do what you want by calling your script again with a fourth parameter:

if [ -z "$4" ]; then
   $0 "$1" "$2" "$3" "$3"
   exit $?
echo $4

Calling above script like ./script.sh one two three will output:


This can be done with an assignment directly into an auxiliary array with an export/import type mechanism:

set a b c "d e f" g h    
thisArray=( "[email protected]" )
set -- "${thisArray[@]}"
echo "[email protected]"

outputs ‘a b c 4 g h’

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.