Command-Line Arguments
Shell scripts can accept command-line arguments and options just
like other Linux commands. (In fact, some common Linux commands
are scripts.) Within your 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
Get Linux Pocket Guide, 2nd Edition 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.