Working with Command Line Arguments in Shell Scripting

Command-line arguments in shell scripting allow you to pass information to your script when you run it from the command line. These arguments can be used to customise the behavior of your script without modifying the script itself. Here’s a detailed explanation of command-line arguments in shell scripting:

Syntax for Command-Line Arguments:

When you run a shell script, you can pass arguments to it in the following way:

./script.sh arg1 arg2 arg3 ...
  • ./script.sh: This is the command to execute your shell script. Replace script.sh with the actual name of your script.
  • arg1, arg2, arg3, …: These are the command-line arguments you’re passing to your script.

Accessing Command-Line Arguments:

Inside your shell script, you can access the command-line arguments using special variables:

  • $0: The name of the script itself (i.e., script.sh).
  • $1, $2, $3, …: These variables represent the first, second, third, and so on, command-line arguments.
  • $@: Represents all the command-line arguments as a single string.
  • $#: The total number of command-line arguments.

Example:

Bash
#!/bin/bash

echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"
echo "Total number of arguments: $#"

If you run this script with ./script.sh arg1 arg2, it will output:

Bash
Script name: ./script.sh
First argument: arg1
Second argument: arg2
All arguments: arg1 arg2
Total number of arguments: 2

Using Command-Line Arguments in a Script:

You can use command-line arguments to customize the behavior of your script. For example, you might use them to specify file names, directories, options, or any other parameters your script needs.

Bash
#!/bin/bash

file=$1

if [ -f $file ]; then
    echo "File $file exists."
else
    echo "File $file does not exist."
fi

In this example, the script expects a filename as the first argument. It checks if the file exists and prints a message accordingly.

Handling Multiple Arguments:

You can use loops to process multiple command-line arguments.

Bash
#!/bin/bash

for arg in "$@"
do
    echo "Argument: $arg"
done

If you run this script with ./script.sh arg1 arg2 arg3, it will output:

Bash
Argument: arg1
Argument: arg2
Argument: arg3

Error Handling and Validation:

It’s important to validate command-line arguments to ensure they are in the expected format and range. You can use conditional statements (if-else) and other control structures to handle different cases.

Using Getopts (Option Parsing):

getopts is a command in Unix and Unix-like operating systems that helps shell scripts to parse command-line options (flags) and arguments. It’s a way to handle options and arguments in a more structured and standard way. It’s particularly useful when you want to provide various options and flags to your script.

For more complex scripts with multiple options and flags, you can use the getopts command to parse command-line arguments. It allows you to define flags and options with corresponding values.

Syntax

Bash
while getopts "options" opt; do
    case $opt in
        option1)
            # Code to handle option1
            ;;
        option2)
            # Code to handle option2
            ;;
        \?)
            echo "Invalid option: -$OPTARG"
            exit 1
            ;;
    esac
done

  • options: A string containing the recognized options (flags) for your script. Each option is represented by a single character, followed by a colon if it requires an argument.
  • opt: This variable will hold the currently processed option.
  • case ... esac: The case statement is used to match the currently processed option to a specific action.
  • option1), option2): These are the recognized options. You should have a case for each option you expect.
  • ;;: Marks the end of a case block. It’s important to include this to prevent “fall-through” (i.e., executing code for subsequent cases if a match is found).
  • \?): This matches an unknown option. It’s used to handle cases where an unsupported or invalid option is provided.
  • OPTARG: This variable contains the value of the argument associated with an option.

Example with Getopts:

Bash
#!/bin/bash

while getopts ":a:b:c:" opt; do
  case $opt in
    a) arg_a="$OPTARG";;
    b) arg_b="$OPTARG";;
    c) arg_c="$OPTARG";;
    \?) echo "Invalid option -$OPTARG";;
  esac
done

echo "Option a: $arg_a"
echo "Option b: $arg_b"
echo "Option c: $arg_c"

With this script, you can run ./script.sh -a value1 -b value2 -c value3 to specify options and their values.

Executing Script:

Bash
./script.sh -a apple -b banana -c cherry

Output:

Bash
Option a: apple
Option b: banana
Option c: cherry

Command-line arguments are a powerful way to make your scripts more versatile and adaptable to different use cases without the need to modify the script itself. They are widely used in shell scripting to provide flexibility and customisation.

Share
OpenLib .

OpenLib .

The Founder - OpenLib.io

You may also like...