Bash Shell: Check for optional arguments

One day, I got sick of typing up the whole command over and over.

I needed to write a script that took in one mandatory argument and a second optional argument.

To make the second argument optional, use the "-z" operator checks if a string is empty. The "-n" operator checks for the string being not empty.

if [ -z "$1" ]; then
echo "You need at least 1 argument"
exit 1
fi

if [ -z "$2" ]; then
DOMAIN=$1
else
DOMAIN=$2
fi

CMD="command something $1 -some -flags $DOMAIN"
echo $CMD
$CMD

Remember to "chmod +x filename" to make it executable.

Now you can begin performing all crazy sorts of bash-fu.

PowerPunch

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog