Passing Arguments to the Script

LinuxLinuxBeginner
Practice Now

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

Introduction

When writing scripts in Shell programming, you can pass arguments to the script when executing it. These arguments can be accessed within the script using special variables. This tutorial will guide you on how to pass arguments to a Shell script and how to handle and use them within the script.

Define the script and access the arguments

Create a new file and save it with ~/project/arguments.sh.

Inside the script, you can access the passed arguments using special variables. The $1 variable references the first argument, $2 references the second argument, and so on. The $0 variable holds the name of the script itself.

#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"

Execute the script with arguments

To execute the script, simply run the following command in your terminal, replacing the arguments with your own values:

cd ~/project
chmod +x arguments.sh
./arguments.sh argument1 argument2
Script name: ./arguments.sh
First argument: argument1
Second argument: argument2

Handle multiple arguments

You can handle multiple arguments by accessing the variables $1, $2, $3, and so on, depending on the number of arguments passed.

#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "Third argument: $3"
$ ./arguments.sh argument1 argument2 argument3
Script name: ./arguments.sh
First argument: argument1
Second argument: argument2
Third argument: argument3

Use the $## variable

The $## variable holds the number of arguments passed to the script. You can use it to check the number of arguments and perform different actions based on that.

#!/bin/bash
if [ $## -eq 0 ]; then
  echo "No arguments passed."
elif [ $## -eq 1 ]; then
  echo "Only one argument passed."
else
  echo "Multiple arguments passed."
fi
$ ./arguments.sh
No arguments passed.
$ ./arguments.sh argument1
Only one argument passed.
$ ./arguments.sh argument1 argument2
Multiple arguments passed.

Use the $@ variable

The $@ variable holds a space-delimited string of all the arguments passed to the script. You can use it to loop through all the arguments and perform actions on each one.

#!/bin/bash
for arg in $@; do
  echo "Argument: $arg"
done
$ ./arguments.sh argument1 argument2 argument3
Argument: argument1
Argument: argument2
Argument: argument3

Summary

In this tutorial, you have learned how to pass arguments to a Shell script and how to handle and use them within the script. You now know how to access the arguments using the $1, $2, and $3 variables, and how to check the number of arguments using the $## variable. You have also learned how to loop through all the arguments using the $@ variable.

Other Linux Tutorials you may like