Command-Line Arguments in Bash with Examples

Pranav T
3 Min Read

Bash scripting is a cornerstone of automation and system management. A powerful feature of Bash is the ability to pass command-line arguments to scripts, making them versatile and dynamic. This blog will explain how arguments work in Bash using a practical example.

The Example Script

Here’s a script that takes a directory name as an argument and counts the number of objects (files and subdirectories) it contains:

Bash
#!/bin/bash

lines=$(ls -l $1 | wc -l)

if [ $# -ne 1 ]
then
    echo "Enter one directory name please try again"
    exit 1
fi

echo "There are $(($lines-1)) objects in $1"

How the Script Works

  • $1 represents the first argument passed to the script, which should be the name of a directory.
  • ls -l $1 lists the directory contents in long format.
  • wc -l counts the number of lines in the output.
  • The script subtracts one from the total line count to exclude the header line from ls -l.
  • if [ $# -ne 1 ] checks if exactly one argument is provided ($# represents the number of arguments).
  • If not, the script prints an error message and exits with exit 1 to indicate failure.
  • If the correct number of arguments is supplied, the script prints the number of objects in the specified directory.

Usage

  1. Save the script to a file, such as count_objects.sh.
  2. Make it executable
Bash
chmod +x count_objects.sh
  1. Run the script with a directory name as an argument
Bash
./count_objects.sh /var
  1. If successful, it outputs
Bash
There are X objects in /var
  1. If no or multiple arguments are provided, it displays
Bash
Enter one directory name please try again

Special Variables

  • $0: The name of the script itself.
  • $1, $2, …: Positional parameters representing the first, second, and subsequent arguments.
  • $#: The number of arguments passed to the script.
  • $* or “$@”: All arguments passed to the script.

Final thoughts

Command-line arguments make Bash scripts flexible and powerful. By understanding how to use special variables and validate input, you can create robust scripts tailored to different tasks. Try enhancing the example script to further improve your Bash scripting skills.

Share This Article