output=$1 # either text or htmlHowever, 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}OR (see my comment below):
echo $output
output=${1:-text}Try another example at a shell prompt:
echo $output
$ vech=Bus
$ echo ${vech-Car}
$ echo ${vech:-Car}
$ unset vech
$ echo ${vech-Car}
$ echo ${vech:-Car}
Finally, here is a sample script:
#!/bin/bashNow, run it as follows:
output=${1-text}
echo "Setting output to $output..."
$ ./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