Passing Arguments to the Script

ShellShellBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Shell programming, the ability to pass arguments to a script is a fundamental and powerful feature. It allows scripts to be more flexible and reusable by accepting input from the command line. This lab will guide you through the process of creating a Shell script that can accept and use command-line arguments. You will learn how to access these arguments within your script, handle multiple arguments, and use special variables to process them efficiently.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL shell(("`Shell`")) -.-> shell/ControlFlowGroup(["`Control Flow`"]) linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) shell(("`Shell`")) -.-> shell/BasicSyntaxandStructureGroup(["`Basic Syntax and Structure`"]) shell(("`Shell`")) -.-> shell/VariableHandlingGroup(["`Variable Handling`"]) shell/ControlFlowGroup -.-> shell/if_else("`If-Else Statements`") linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/BasicFileOperationsGroup -.-> linux/touch("`File Creating/Updating`") linux/BasicFileOperationsGroup -.-> linux/chmod("`Permission Modifying`") shell/BasicSyntaxandStructureGroup -.-> shell/shebang("`Shebang`") shell/BasicSyntaxandStructureGroup -.-> shell/comments("`Comments`") shell/VariableHandlingGroup -.-> shell/variables_usage("`Variable Usage`") shell/ControlFlowGroup -.-> shell/for_loops("`For Loops`") subgraph Lab Skills shell/if_else -.-> lab-385383{{"`Passing Arguments to the Script`"}} linux/echo -.-> lab-385383{{"`Passing Arguments to the Script`"}} linux/touch -.-> lab-385383{{"`Passing Arguments to the Script`"}} linux/chmod -.-> lab-385383{{"`Passing Arguments to the Script`"}} shell/shebang -.-> lab-385383{{"`Passing Arguments to the Script`"}} shell/comments -.-> lab-385383{{"`Passing Arguments to the Script`"}} shell/variables_usage -.-> lab-385383{{"`Passing Arguments to the Script`"}} shell/for_loops -.-> lab-385383{{"`Passing Arguments to the Script`"}} end

Create a new script file

Let's start by creating a new script file. We'll use the WebIDE (VS Code) for this lab.

  1. Open the WebIDE if it's not already open.
  2. In the file explorer on the left, navigate to the /home/labex/project directory.
  3. Right-click in the file explorer and select "New File".
  4. Name the new file arguments.sh.

Now that we have created the file, let's add the basic structure of our script:

#!/bin/bash

## Your code will go here

The first line is called the "shebang" or "hashbang". It tells the system which interpreter to use to execute the script. In this case, we're using bash.

For beginners: The shebang line is important because it allows you to run the script directly (like ./arguments.sh) instead of having to type bash arguments.sh every time. It's a small detail, but it makes your scripts more convenient to use.

Access script arguments

Now, let's modify our script to access and display the arguments passed to it. In Shell scripting, special variables are used to access command-line arguments:

  • $0 represents the name of the script itself
  • $1, $2, $3, etc., represent the first, second, third arguments, and so on

Add the following code to your arguments.sh file:

#!/bin/bash

echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "Third argument: $3"

This script will display the script name and the first three arguments passed to it.

For beginners:

  • The $ symbol is used to reference variables in bash.
  • $0, $1, $2, etc., are special variables that bash automatically sets for you when you run a script with arguments.
  • If you run the script without any arguments, $1, $2, and $3 will be empty, but the script will still run without errors.

Make the script executable

Before we can run our script, we need to make it executable. This is done using the chmod command. In the terminal, navigate to the project directory and run the following command:

cd /home/labex/project
chmod +x arguments.sh

The chmod +x command adds execute permissions to the file, allowing it to be run as a script.

For beginners:

  • chmod stands for "change mode". It's used to change the permissions of a file or directory.
  • The +x option adds the execute permission. This is necessary for bash to be able to run the file as a script.
  • If you forget this step, you'll get a "permission denied" error when trying to run your script.

Execute the script with arguments

Now that our script is executable, let's run it with some arguments. In the terminal, execute the following command:

./arguments.sh hello world example

You should see output similar to this:

Script name: ./arguments.sh
First argument: hello
Second argument: world
Third argument: example

This output shows that our script successfully accessed and displayed the command-line arguments.

For beginners:

  • The ./ before the script name tells bash to look for the script in the current directory.
  • Each word after the script name becomes a separate argument. In this case, "hello" is the first argument, "world" is the second, and "example" is the third.
  • If you want to pass an argument with spaces, you need to use quotes, like this: ./arguments.sh "hello world" example

Handle the number of arguments

Let's modify our script to handle different numbers of arguments. We'll use the $# special variable, which holds the number of arguments passed to the script.

Update your arguments.sh file with the following content:

#!/bin/bash

if [ $## -eq 0 ]; then
  echo "No arguments provided."
elif [ $## -eq 1 ]; then
  echo "One argument provided: $1"
elif [ $## -eq 2 ]; then
  echo "Two arguments provided: $1 and $2"
else
  echo "More than two arguments provided:"
  echo "First argument: $1"
  echo "Second argument: $2"
  echo "Third argument: $3"
  echo "Total number of arguments: $#"
fi

This script uses conditional statements to handle different numbers of arguments.

For beginners:

  • $# is a special variable that contains the number of arguments passed to the script.
  • [ $## -eq 0 ] is a condition that checks if the number of arguments is equal to 0.
  • elif is short for "else if". It allows you to check multiple conditions in sequence.
  • The -eq operator means "equal to". There are other operators like -lt (less than), -gt (greater than), etc.

Test the updated script

Now, let's test our updated script with different numbers of arguments:

./arguments.sh
./arguments.sh one
./arguments.sh one two
./arguments.sh one two three four

You should see different outputs based on the number of arguments provided.

For beginners:

  • Running the script without any arguments (./arguments.sh) will trigger the first condition in our script.
  • Each subsequent command adds more arguments, demonstrating how our script handles different cases.
  • Notice how the script's behavior changes based on the number of arguments. This kind of flexibility is very useful in real-world scripts.

Loop through all arguments

Finally, let's modify our script to loop through all provided arguments using the $@ special variable, which represents all command-line arguments.

Update your arguments.sh file with the following content:

#!/bin/bash

echo "Total number of arguments: $#"
echo "All arguments:"

count=1
for arg in "$@"; do
  echo "Argument $count: $arg"
  count=$((count + 1))
done

This script uses a for loop to iterate through all arguments and display them with their position.

For beginners:

  • $@ is a special variable that contains all the arguments passed to the script.
  • The for loop is used to iterate over a list of items. In this case, it's iterating over all the arguments.
  • $((count + 1)) is arithmetic expansion in bash. It's used to increment the count variable.
  • This script will work with any number of arguments, making it more flexible than our previous versions.

Test the final script

Let's test our final script with multiple arguments:

./arguments.sh apple banana cherry date

You should see output similar to this:

Total number of arguments: 4
All arguments:
Argument 1: apple
Argument 2: banana
Argument 3: cherry
Argument 4: date

This demonstrates that our script can now handle any number of arguments and display them all.

For beginners:

  • This final version of the script is much more flexible than our earlier versions.
  • It can handle any number of arguments, from zero to many.
  • The script now numbers each argument, which can be very useful in more complex scripts.
  • Try running the script with different numbers of arguments to see how it behaves.

Summary

In this lab, you have learned how to create a Shell script that can accept and process command-line arguments. You've explored several key concepts:

  1. Creating and making a script executable
  2. Accessing individual arguments using special variables ($1, $2, etc.)
  3. Using the $## variable to determine the number of arguments
  4. Implementing conditional logic to handle different numbers of arguments
  5. Using the $@ variable to loop through all provided arguments

These skills are fundamental in Shell scripting and will allow you to create more flexible and powerful scripts that can adapt to different inputs. As you continue to develop your Shell scripting skills, you'll find that the ability to handle command-line arguments is crucial for creating versatile and reusable scripts for various tasks in system administration and automation.

Other Shell Tutorials you may like