Using Parameters in a Shell Script
Problem
You also want users to be able to invoke your script with a parameter. You could require that users set a shell variable, but that seems clunky. You also need to pass data to another script. You could agree on environment variables, but that ties the two scripts together too closely.
Solution
Use command-line parameters. Any words put on the command line of a shell script are available to the script as numbered variables:
# simple shell script echo $1
The script will echo the first parameter supplied on the command line when it is invoked. Here it is in action:
$ cat simplest.sh # simple shell script echo ${1} $ ./simplest.sh you see what I mean you $ ./simplest.sh one more time one $
Discussion
The other parameters are available as ${2}, ${3}, ${4}, ${5}
, and so on. You don’t
need the braces for the single-digit numbers, except to separate the
variable name from the surrounding text. Typical scripts have only a
handful of parameters, but when you get to ${10}
you better use the braces or else the
shell will interpret that as ${1}
followed immediately by the literal string 0
as we see here:
$ cat tricky.sh echo $1 $10 ${10} $ ./tricky.sh I II III IV V VI VII VIII IX X XI I I0 X $
The tenth argument has the value X
but if you write $10
in your script, then the shell will give
you $1
, the first parameter, followed
immediately by a zero, the literal character that you put next to the
$1
in your echo
statement.
Get bash Cookbook 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.