- Unix Commands Reference
- Unix Commands - Home
builtins - Unix, Linux Command
NAME
bash, :, ., [, alias, bg, bind, break, builtin, cd, command, compgen, complete, continue, declare, dirs, disown, echo, enable, eval, exec, exit, export, fc, fg, getopts, hash, help, history, jobs, kill, let, local, logout, popd, printf, pushd, pwd, read, readonly, return, set, shift, shopt, source, suspend, test, times, trap, type, typeset, ulimit, umask, unalias, unset, wait - bash built-in commands, see bash(1)BASH BUILTIN COMMANDS
[Include document man1/bash.1]
EXAMPLES
Consider below bash script
#!/bin/bash showDate=0 while getopts ":f:s:p:a:d" opt; do case "${opt}" in f) fileName=${OPTARG} ;; s) sourceDir=${OPTARG} ;; p) destinationDir=${OPTARG} ;; a) action=${OPTARG} ;; d) showDate=1 ;; *) echo "Internal error!" ; exit 1 ;; esac done # Now take action if [ ${showDate} = 1 ]; then echo "Today's date: " `date` fi echo "$action file $fileName from $sourceDir to $destinationDir"
This script has below 5 parameters:
-f: File name -s: File source -p: destination path -a: Action -d: Optional, Display date or not
getopts does not support long options like getopt, nor does it support optional arguments.
Below are few combinations of options in which script can be called
1. Specify all parameters
$ ./getopts.sh -f MyTest.txt -s /home -p /usr/bin -a Copy -d Today's date: Sat Feb 13 02:32:29 IST 2016 Copy file MyTest.txt from /home to /usr/bin
2. Omit optional parameter
$ ./getopts.sh -f MyTest.txt -s /home -p /usr/bin -a Copy Copy file MyTest.txt from /home to /usr/bin
3. If the options string start with : (ex. ":f:s:p:a:d") then the system generated error message is suppressed
$ ./getopts.sh -f MyTest.txt -s /home -p /usr/bin -a Internal error!
4. If the options string does not start with : (ex. "f:s:p:a:d") then the system generated error message is shown
$ ./getopts.sh -f MyTest.txt -s /home -p /usr/bin -a ./getopts.sh: option requires an argument -- a Internal error!
Advertisements