• 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
   4=$3
fi

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
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.

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 $?
fi
echo $4

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

three

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]" )
thisArray[3]=4
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.