Home‎ > ‎CIS 98‎ > ‎

Passing Arguments

  1. Positional Parameters
    A shell script, or a shell function, accesses the command line arguments via the Positional Parameters:
    • $#   - the number of arguments on the command-line not counting the name of the command.
    • $0   - the name of the program as it was invoked.
    • $1   - the first argument/option on the command-line
    • $2   - the second positional parameter
    • $3   - the third positional parameter
      ...
    • $*   - all the positional parameters together
    • "$@"   - each positional parameter separately quoted
    Exercise 1

    The shift statement causes positional parameters 1 through n to shift down one position. $# is also decremented by this operation.

    The set command sets the positional parameters of the current shell to the arguments on the command line.

  2. The Shell Environment and Scope
    The total of all defined variables, both user-defined and program defined.
    Be careful of name space pollution.
    1. Most variables are global within the script.
    2. Positional Parameters are local to the main program or the function within which they apply.
    3. Exported variables may be passed on to child subshells, but they don't share the same data space; they are copies, not links.
  3. Command Grouping
    1. Functions: { }
    2. Subshells: ( )
    3. External processes (Parent/Child)

  4. Command Return Codes
    Every UNIX command, or shell statement, has a return code indicating its success or failure.
    • Return code of zero (0) indicates success.
      The true command always returns 0
    • A return code of non-zero indicates failure.
      The false command always returns -1
    • These return codes may be found in the shell variable, $?.
      The contents of this variable are over-written with every command.

Exercise 1: Passing Arguments to Programs

Write a one line script called ison which takes one argument: the name of a user. The ison program should output all instances of that user currently logged on according to the who command. If the user is not logged on, there should be no output.

Exercise 2: Passing Arguments to Functions

Type the following program to a file called mycolor and invoke it with the arguement "red". See if you can predict the results.
#!/bin/bash
yourcolor()
{
	echo $1
}
echo $1
yourcolor blue
echo $1
exit 0

Comments