Command-Line Arguments
Shell scripts can accept command-line arguments just like other commands.[37] Within a shell script, you can refer to these arguments as $1
, $2
, $3
, and so on:
➜cat myscript
#!/bin/bash echo "My name is $1 and I come from $2" ➜./myscript Johnson Wisconsin
My name is Johnson and I come from Wisconsin ➜./myscript Bob
My name is Bob and I come from
Your script can test the number of arguments it received with
$#
:
if [ $# -lt 2 ] then echo "$0 error: you must supply two arguments" else echo "My name is $1 and I come from $2" fi
The special value $0
contains
the name of the script, and is handy for usage and error
messages:
➜./myscript Bob
./myscript
error: you must supply two arguments
To iterate over all command-line arguments, use a for
loop with the special variable $@
, which holds all arguments:
for arg in $@ do echo "I found the argument $arg" done
[37] To a shell script, there is no difference between an option and an argument. They are all considered arguments.
Get Macintosh Terminal Pocket Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.