Skip to Main Content
Linux Pocket Guide
book

Linux Pocket Guide

by Daniel J. Barrett
February 2004
Beginner content levelBeginner
200 pages
5h 40m
English
O'Reilly Media, Inc.
Content preview from Linux Pocket Guide

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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux Pocket Guide, 2nd Edition

Linux Pocket Guide, 2nd Edition

Daniel J. Barrett
Linux in a Nutshell, 6th Edition

Linux in a Nutshell, 6th Edition

Ellen Siever, Stephen Figgins, Robert Love, Arnold Robbins

Publisher Resources

ISBN: 9780596806347Errata Page