C Shell Scripting/Parameters

From Wikibooks, open books for an open world
Jump to: navigation, search

Passing parameters to a script[edit]

In scripts, the variables $0, $1, $2, and so on are known as positional parameters. The variable $0 refers to the name of the command and $1, $2 and greater will be the parameters passed into the script.

When a csh script is invoked, the special variable argv is set to the wordlist of arguments given on the command line. Thus, as alternatives to the special variables $1, $2 and so on, csh scripts can use $argv[1], $argv[2], and so on to access command line arguments. The value of the variable $#argv is the number of arguments given.

For example write a myparams script:

#!/bin/csh -f
echo The $0 command is called with $#argv parameters
echo   parameter 1 is $1
echo   parameter 2 is $2
echo   parameter 3 is $3
echo   parameter 4 is $4
echo All Parameters are \"$argv\"
echo 2nd and on parameters are \"$argv[2-]\" 

then run the command:

./myparams alpha beta omega

This prints out the following:

The ./myparams command is called with 3 parameters
parameter 1 is alpha
parameter 2 is beta
parameter 3 is omega
parameter 4 is
All Parameters are "alpha beta omega"
2nd and on parameters are "beta omega"

If the parameter is missing the value of the position parameter will be a blank string as is the case of the 4th parameter. Also, you can get the entire or part of the command-line using the variable $argv which is a wordlist.

If you want to include spaces in a single parameter you must quote the value. For example running this command:

./myparams "alpha beta" omega

would print out the following:

The ./myparams command is called with 2 parameters
parameter 1 is alpha beta
parameter 2 is omega
parameter 3 is
parameter 4 is
All Parameters are "alpha beta omega"
2nd and on parameters are "omega"

The alpha and beta value are not combined as a single value.

Lessons[edit]

  1. Parameters passed to a script are accessible using numbered variables like $1, $2, $3 and so on.
  2. Parameters passed to a script are also accessible using wordlist variable called $argv