Differences

This shows you the differences between two versions of the page.

Link to this comparison view

getopt [2013/08/27 16:47]
getopt [2013/08/27 16:47] (current)
Line 1: Line 1:
 +====== getopt ======
  
 +  * [[bash]]
 +  * [[getopts]]
 +  * [[sh]]
 +
 +Generally speaking, use ''​getopts''​ since it is newer and a built-in function of bash.  Use ''​getopt''​ if you are looking for consistency across platforms.
 +
 +The man page has a good example, but here are some of the basics:
 +
 +Use **-a:** to requires an argument, either directly after the ''​-a''​ or with a whitespace first.
 +
 +<​code>​
 +getopt a: $*
 +</​code>​
 +
 +Use **-b** to set a boolean value.
 +
 +<​code>​
 +getopt b $*
 +</​code>​
 +
 +=== getopt example ===
 +
 +<code bash>
 +# Allow -a <​arg>,​ -d and -z
 +args=`getopt a:vz $*`
 +
 +# If getopt fails, then throw an error and quit
 +if [ $? -ne 0 ]; then echo "​Usage:​ ... "; exit 1; fi
 +
 +# Set the new arguments
 +set -- $args
 +
 +while true; do
 +  case "​$1"​ in
 +  -a)
 +    echo "​Passed '​$2'​ argument to -a"; shift; shift;;
 +  -v)
 +    echo "​Verbose output enabled";​ verbose=1; shift;;
 +  -z)
 +    echo "Debug output enabled";​ verbose=1; debug=1; shift;;
 +  --)
 +    shift; break;;
 +  esac
 +done
 +</​code>​