Arbitrary Command-Line Arguments In Bash

|

Have you ever wanted to be able to process an arbitrary number of command-line arguments in your Bash scripts? Well, fear not! It is actually quite easy. All you need is one of the special built-in variables of the Bash shell. The “$@” variable gives you the parameters passed on without any expansion and seen as separate words. This means you can iterate through them without much fuss.

#!/bin/bash

if [ -z "$1" ]; then
  echo -e "\nUsage: `basename $0` arg 1 [arg 2] [etc.]..."
  exit 1
fi

echo "Found $# Command-Line Arguments"

idx=1
for arg in "$@"
do
  echo "Arg[$idx] = ${arg}"
  let "idx += 1"
done

exit 0

The first part of this script uses the “-z” test to see if the first positional command-line argument is null. If it is then the script simply outputs a usage statement and exits with a non-zero return value. Otherwise the script goes into a for loop which simply outputs the value of each command-line argument in turn. Notice I also used the “$#” internal variable which simply gives you the number of command-line arguments passed.

So as a side-note I could actually have used this variable to test for the existence of command-line arguments instead of “-z”. I would just do it like this instead:

if [ "$#" -eq 0 ]; then
  echo -e "\nUsage: `basename $0` arg 1 [arg 2] [etc.]..."
  exit 1
fi

Well, happy Bashing!