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 $* gives 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). Go ahead and type the above script in a file named lc.sh to try it out. Don't forget that shell scripts need to be set executable - chmod +x <script>.

Here is an example usage:

[alice@onyx shell-examples]: lc.sh *
3 files
      5 hello.sh
      6 lc.sh
      3 numusers
     14 total
[alice@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.