Getopts Arguments in Shell
Level 5217 keystrokes
getopts reads command-line options one at a time in a while loop, and case handles each one; OPTARG holds an option's argument. The output shown is for a run with -h.
Shell code
# Leading : = silent errors; f: and o: take an argument; v and h are flags# Each call puts the next option letter in opt; the loop ends when none are left1while getopts ":f:o:vh" opt; do2 case $opt in # -f FILE: OPTARG holds the value given after -f3 f) input_file="$OPTARG" ;; # -o FILE sets the output file4 o) output_file="$OPTARG" ;; # -v turns on verbose mode5 v) verbose=true ;; # -h prints the usage line6 h) echo "Usage: script -f file -o output [-v]" ;; # Unknown option: opt is ?, escaped as \? so it is not a wildcard; OPTARG holds the letter7 \?) echo "Invalid option: -$OPTARG" ;;8 esac9doneOutput
Usage: script -f file -o output [-v]
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Shell code and how often they appear.
;× 11"× 10:× 5)× 5-× 4$× 4=× 3_× 2?× 1[× 1