Mark Lucernas
2020-08-13

Arguments

Argument Variables

  • $1 – First argument
  • $2 – Second argument
  • $# – Number of all command line arguments passed in
  • $@ – Array of all command line arguments

Using Shift Command

The shift command is one of the Bourne shell built-ins that comes with Bash. This command takes one argument, a number. The positional parameters are shifted to the left by this number, N. The positional parameters from N+1 to $# are renamed to variable names from $1 to $# - N+1.

Check For Arguments

Check exit if command line argument was passed in

if [[ $# -lt 1 ]]; then
  echo "Must provide argument(s)"
  exit 1
fi

Looping Over Arguments

Looping over all command line arguments

while test ${#} -g 0; do
  echo $1
  shift
done

# or

while (($#)); do
  echo $1
  shift
done"

# or

for i in "${@}"; do
  echo "$i"
done

Looping over command line arguments except first one

shift

while test ${#} -g 0; do
  echo $1
  shift
done

# or

for i in "${@:2}"; do
  echo "$i"
done


Resources