Monday, April 30, 2012

Shell Scripting: If Variable Is Not Defined, Set Default Variable

If var is defined AND NOT EMPTY, use var, otherwise set a default variable under Bash. For e.g. my script needs a parameter for output variable. It can be text or html. I set it as follows in my script
output=$1 # either text or html
However, sometime user forget to pass the parameter to my shell script and my enter logic fails. So how do I set default value to text, if no parameter passed?

BASH, POSIX shell, and Korn (all versions) support the parameter expansion and testing. For e.g. if $1 is defined AND NOT EMPTY, use $1; otherwise, set to "text", enter:
output=${1-text}
echo $output
OR (see my comment below):
output=${1:-text}
echo $output
Try another example at a shell prompt:
$ vech=Bus
$ echo ${vech-Car}
$ echo ${vech:-Car}
$ unset vech
$ echo ${vech-Car}
$ echo ${vech:-Car}

Finally, here is a sample script:
#!/bin/bash
output=${1-text}
echo "Setting output to $output..."
Now, run it as follows:
$ ./script.sh html
$ ./script.sh text
$ ./script.sh

You can also force to user to pass the parameter:
#!/bin/bash
output=${1-text}
[ $# -eq 0 ] && { echo "Usage: $0 format" ; exit 1; }
echo "Setting output to $output..."

No comments:

Post a Comment