Home Linux How to Read Command Line Arguments in Shell Scripts

How to Read Command Line Arguments in Shell Scripts

by Anup Maurya
17 minutes read
How to Read Command Line Arguments in Shell Scripts

Shell scripts are powerful tools for automating tasks and running commands in a Unix-like environment. Often, you may want to pass arguments to your shell script to customize its behavior. Command line arguments allow you to provide input to a shell script when executing it.

Let’s go through the steps to read command line arguments in a shell script:

Step 1: Create a new shell script

Create a new file with a .sh extension, for example, script.sh. You can use any text editor to create the script.

Step 2: Define the shebang

At the beginning of the script, you need to specify the interpreter to use. In this case, we’ll use the bash shell. Add the following line as the first line of your script:

#!/bin/bash

Step 3: Accessing command line arguments

To access the command line arguments, you can use special variables provided by the shell. The main variables are:

  • $0 – The name of the script itself.
  • $1, $2, $3, … – The first, second, third, and subsequent arguments passed to the script.

You can access these variables within your script to use the provided arguments.

Step 4: Reading and using command line arguments

You can read and use the command line arguments using the special variables mentioned above. Here’s an example script that demonstrates how to read and use command line arguments:

#!/bin/bash

echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"

# You can use the arguments in your script logic
echo "Total number of arguments: $#"

# You can also iterate over the arguments
echo "Iterating over arguments:"
for arg in "$@"; do
    echo "$arg"
done

In the above script, we use echo statements to print the script name, the first and second arguments, and all the arguments passed to the script. We also demonstrate how to get the total number of arguments using $# and how to iterate over the arguments using a for loop.

Step 5: Execute the script

Save the script file and make it executable by running the following command in your terminal:

chmod +x script.sh

Now you can execute the script by typing its name, followed by the arguments you want to pass:

./script.sh arg1 arg2

Replace script.sh with the actual name of your script, and arg1 and arg2 with the desired arguments.

That’s it! You now know how to read command line arguments in shell scripts. You can use this technique to customize the behavior of your scripts based on the input provided by the user.

related posts

Leave a Comment