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 left
1while getopts ":f:o:vh" opt; do
2 case $opt in
# -f FILE: OPTARG holds the value given after -f
3 f) input_file="$OPTARG" ;;
# -o FILE sets the output file
4 o) output_file="$OPTARG" ;;
# -v turns on verbose mode
5 v) verbose=true ;;
# -h prints the usage line
6 h) echo "Usage: script -f file -o output [-v]" ;;
# Unknown option: opt is ?, escaped as \? so it is not a wildcard; OPTARG holds the letter
7 \?) echo "Invalid option: -$OPTARG" ;;
8 esac
9done

Output

Usage: script -f file -o output [-v]
Practice typing this code

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

More Shell examples at level 5

← Shell typing practice