next up previous contents
Next: Program output as an Up: Shell programming Previous: Creating new commands   Contents

Command arguments and parameters

When a shell script runs, the variable $1 is the first command line argument, $2 is the second command line argument and so on. The variable $0 stores the name of the script. The variable $ all the arguments separated by spaces as one string. The variable $# gives the number of command line arguments. The use of a dollar sign means to use the value of a variable.

The following example script counts the number of lines in all files given in the command line.

#!/bin/sh
# lc.sh

echo $# files
wc -l $*

Note the # sign is a comment in the second line of the script. The # comment sign can be used anywhere and makes the rest of the line a comment. The command echo outputs its arguments as is to the console (the $# gets converted to the number of command line arguments by the shell). Here is an example usage:

[amit@onyx shell-examples]: lc.sh *
3 files
      5 hello.sh
      6 lc.sh
      3 numusers
     14 total
[amit@onyx shell-examples]:

The simple script assumes that all names provided on the command line are regular files. However, if some are directories, then wc will complain. A better solution would be to test for regular files and only count lines in the regular files. For that we need an if statement, which we will cover in a later section.


next up previous contents
Next: Program output as an Up: Shell programming Previous: Creating new commands   Contents
Amit Jain 2013-04-22