Argument Processing in Shell

Level 4140 keystrokes

Special variables give a script its name ($0), argument count ($#), all arguments ($@), single arguments ($1, $2) and the last exit status ($?). The output assumes the script is run as ./script.sh foo bar baz.

Shell code

# $0 is the name the script was called with: ./script.sh
1echo "Script: $0"
# $# is the number of arguments: 3
2echo "Total args: $#"
# $@ expands to all arguments: foo bar baz
3echo "All args: $@"
# $1 and $2 are the first and second arguments
4echo "First: $1, Second: $2"
# shift drops $1 and moves the rest left ($2 becomes $1)
5shift
# Now $1 is bar
6echo "After shift: $1"
# $? is the exit status of the previous command (the echo above): 0
7echo "Exit status: $?"

Output

Script: ./script.sh
Total args: 3
All args: foo bar baz
First: foo, Second: bar
After shift: bar
Exit status: 0
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.

  • "× 12
  • :× 7
  • $× 7
  • ,× 1
  • ?× 1
  • @× 1
  • #× 1

More Shell examples at level 4

← Shell typing practice