Bash Shell: Check for optional arguments

0 Comments

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.

01.if [ -z "$1" ]; then
02.  echo "You need at least 1 argument"
03.  exit 1
04.fi
05. 
06.if [ -z "$2" ]; then
07.  DOMAIN=$1
08.else
09.  DOMAIN=$2
10.fi
11. 
12.CMD="command something $1 -some -flags $DOMAIN"
13.echo $CMD
14.$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