Command line arguments allow Bash scripts to accept dynamic user input. Instead of hardcoding values, scripts can flexibly process arguments for reusable logic. This comprehensive guide covers various methods for accessing and handling arguments in Bash.

What Are Command Line Arguments?

Command line arguments (also called positional parameters) are values passed when executing a script:

./script.sh arg1 arg2 arg3

Here arg1, arg2, arg3 etc. are command line arguments made available for the Bash script.

The main benefits are:

  • Flexibility – Scripts accept inputs for reusable logic across files, users etc.
  • Customization – Users can control script behavior by passing different cli values.
  • Modularity – Modules and functions can accept arguments for isolated logic.

Accessing Arguments with Variables

Bash makes command line arguments available through special variables:

  • $1 – Holds 1st argument
  • $2 – Holds 2nd argument
  • $3 – Holds 3rd argument
  • …and so on till $9

Consider a script math.sh:

#!/bin/bash

num1=$1
num2=$2

sum=$((num1 + num2))
echo $sum

When executed with:

./math.sh 10 20

It outputs:

30

By using $1 and $2, the script accepts numeric cli arguments for the sum calculation instead of hardcoded numbers.

Special Argument Variables

Some special variables help access all arguments:

  • $@ – References all arguments as separate words
  • $# – Returns number of arguments
  • $0 – Script name

Here is an example script showing these special variables:

#!/bin/bash

echo "Script name: $0"
echo "Number of arguments: $#"
echo "Arguments: $@"

Output on running ./script.sh foo bar 10 20:

Script name: ./script.sh  
Number of arguments: 4
Arguments: foo bar 10 20

Iterating Over Arguments

To loop through all arguments, either index them like arrays or use a for loop:

#!/bin/bash

# Array style access
echo $1
echo $2 

# Using for loop
for arg in "$@"
do
  echo $arg
done

Output when run with multiple arguments:

firstArg 
secondArg
firstArg
secondArg

This provides flexible access without needing to know exactly how many arguments the user passes.

Handling Options with getopts

For more advanced argument processing, the getopts function helps handle options. Here is its syntax:

getopts <option-spec> <variable-name>

It processes cli flags and values saving the next option letter in <variable-name>. Common option syntax includes:

  • -a – Single letter flag
  • --all – Full word flag
  • -o <value> / --output=<value> – Option accepting value

Consider a script backup.sh that accepts archive options:

#!/bin/bash

verbose=false
while getopts ‘:v‘ option; do
  case $option in
    v) verbose=true;;
    ?) printf "Usage: %s [-v] files...\n" $0
       exit 2;;  
  esac
done 

# ...operate in verbose mode   

When called with -v, it enables verbose mode:

./backup.sh -v file1.txt file2.txt 

This demonstrates getopts processing arguments as flags and customizing script logic accordingly.

Best Practices

Here are some tips for handling command line arguments effectively:

Input Validation

Validate all user supplied arguments before usage. Example to check number of arguments:

# Expect 2 CLI args
if [ "$#" -ne 2 ]; then
  echo "Illegal number of arguments"
  exit 1 
fi

Help Messages

Print a help message when invalid input is detected:

echo "Usage: script.sh -o OUTFILE file ..."
exit 1

Shift

When processing multiple options/arguments in complex flows using while loop over getopts, use shift command to move onto next argument once processed.

Case Style

Use snake_case style for cli arguments to improve readability. For example output_file instead of outputFile.

Combining CLI Arguments and Environment Variables

For production grade scripts destined for wider reuse, instead of relying solely on cli arguments, also utilize environment variables for configuration.

Here is an example demonstrating cli args for runtime values used in conjunction with env vars for preset defaults:

#!/bin/bash

# Default output dir 
OUT_DIR=/var/log 

# Allow override via env var
if [ -n "$OUTPUT_DIR" ]; then
  OUT_DIR="$OUTPUT_DIR" 
fi

# Runtime output file argument
outfile=$1  

# Construct final path
outfile="$OUT_DIR/$outfile"

This showcases environment variables setting ground rules while cli arguments enable customization.

Conclusion

In Bash scripting, command line arguments empower users to control script behavior. This guide provided various examples demonstrating simple and advanced argument handling, best practices to follow and even tips on combining arguments with environment variables. Mastering arguments is key to creating reusable scripts.

Similar Posts