Command Line Arguments in Bash

Posted: 14th June 2014 by Tim in Bash, Linux
Tags: , , , , ,

In Bash, arguments passed in on the command line are stored in numbered variables. For example, the first argument is $1, the second argument is $2, and so on. The total number of arguments passed to the program is stored in $#

$0 contains the path to the program. This path may be an absolute path or a relative path, depending on how you called the script. $@ and $* will return all of the arguments passed to the program.

For example:

#/bin/bash
echo "Execution command: '$0 $@' ($# args)"
echo "First 3 arguments:"
if [ $# -ge 1 ]
then
    echo "  \$1 = $1"
fi
if [ $# -ge 2 ]
then
    echo "  \$2 = $2"
fi
if [ $# -ge 3 ]
then
    echo "  \$3 = $3"
fi

This script will print this if called using a relative path:
Execution command: './command_line_args.sh one two three' (3 args)
First 3 arguments:
  $1 = one
  $2 = two
  $3 = three

Or, if called using an absolute path:
Execution command: '/tmp/command_line_args.sh ichi ni san' (3 args)
First 3 arguments:
  $1 = ichi
  $2 = ni
  $3 = san