June 2012
Beginner
227 pages
5h 43m
English
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 WisconsinMy name is Johnson and I come from Wisconsin ➜./myscript BobMy 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./myscripterror: 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.
Read now
Unlock full access