Positional parameters in Bash are values provided to a script or function when executed. They are accessed using bash parameters like $1, $2, $3, and so on, representing the first, second, third, and subsequent parameters respectively. In this article, I am going to discuss how you can use positional parameters in bash scripting.
Key Takeaways
- Understanding the usability of positional parameters.
- Getting familiar with the set and unset commands, and their functionality with positional parameters.
Free Downloads
What is a Positional Parameter?
Positional parameters refer to the input arguments supplied to your scripts during their execution. These arguments are accessible using variables ranging from $1 to $N, where N represents a numeric value.
In cases where N is comprised of more than a single digit, it should be enclosed within curly braces like ${N}. For example, consider the case where you want to access the value of the 10th positional parameter. You would use ${10} to avoid confusion with ${1}0, which could be mistakenly interpreted as the value of $1 followed by a ‘0‘. So, using ${10} ensures accurate parameter retrieval.
2 Practical Examples of Using Positional Parameters in Bash Scripting
As you have already got an idea of what are the positional parameters. Now let’s see how can you incorporate those parameters in a bash script. For this, I am going to provide 2 different examples of using positional parameters in a script.
Example 01: Performing Arithmetic Operation With Positional Parameters in Bash
In this first example, the script receives a pair of arguments and delivers the outcome of arithmetic operations ( Addition, Subtraction, multiplication, division) performed on these two integers.
❶ At first, launch an Ubuntu Terminal.
❷ Write the following command to open a file in Nano:
nano arithmetic_parameters.sh
- nano: Opens a file in the Nano text editor.
- arithmetic_parameters.sh: Name of the file.
❸ Copy the script mentioned below:
#!/bin/bash
# Check if at least 3 positional parameters are provided
if [ $# -lt 3 ]; then
echo "Usage: $0 <num1> <num2> <operator>"
exit 1
fi
num1=$1
num2=$2
operator=$3
result=0
case $operator in
+) result=$((num1 + num2)); operation="addition" ;;
-) result=$((num1 - num2)); operation="subtraction" ;;
/)
if [ $num2 -eq 0 ]; then
echo "Error: Division by zero is not allowed."
exit 1
fi
result=$((num1 / num2))
operation="division"
;;
*)
result=$((num1 * num2))
operation="multiplication"
;;
esac
echo "Performing $operation: $num1 $operator $num2 = $result"
Using a case statement based on the operator, the script executes the chosen arithmetic operation—addition, subtraction, or multiplication and division—by calculating the result accordingly. Additionally, it addresses division by zero by confirming whether the divisor is zero before proceeding with the division.
❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.
❺ Use the following command to make the file executable:
chmod u+x arithmetic_parameters.sh
- chmod: Changes the permissions of files and directories.
- u+x: Here, u refers to the “user” or the owner of the file and +x specifies the permission being added, in this case, the “execute” permission. When u+x is added to the file permissions, it grants the user (owner) permission to execute (run) the file.
- arithmetic_parameters.sh: File name.
❻ Run the script by the following command:
./arithmetic_parameters.sh 45 5 +
./arithmetic_parameters.sh 45 5 -
If you run the provided script ./arithmetic_parameters.sh 45 5 + with the given command line arguments, the script returns Performing addition: 45 + 5 = 50, and Performing subtraction: 45 – 5 = 40 for ./arithmetic_parameters.sh 45 5 –.
Example 02: Set or Unset Positional Parameters in Bash Script
Using the built-in set command, you can set your positional arguments and double hyphen (—) for unsetting variables. Follow the code I am going to discuss below to learn more.
You can follow the steps of Example 01, to save & make the script executable.
Script (set-unset.sh) >
#!/bin/bash
# From command line
echo -e "Basename=$0"
echo -e "\$1=$1"
echo -e "\$2=$2"
echo -e "\$3=$3"
# From Set builtin
set First Second Third
echo -e "\$1=$1"
echo -e "\$2=$2"
echo -e "\$3=$3"
# Store positional parameters with -(hyphen)
set - -f -s -t
echo -e "\$1=$1"
echo -e "\$2=$2"
echo -e "\$3=$3"
# Unset positional parameter
set --
echo -e "\$1=$1"
echo -e "\$2=$2"
echo -e "\$3=$3"
Next, the script employs the set command with hyphens to set positional parameters (-f, -s, -t). These hyphens are treated as arguments themselves, and the resulting values are shown using echo statements. Finally, the script uses the set command with double hyphens (—) to unset all positional parameters. As a result, subsequent echo statements display empty values for the positional parameters.
Copy and paste the following command to run the script:
./set-unset.sh 25 5 2
Upon executing the provided script ./set-unset.sh with the command line arguments 25 5 2, the output will look like the above image
Assignment Task
Down below, I am going to give you two assignment tasks to learn and try by yourself. Don’t forget to share your experience in the comment section.
- Write a Bash script that takes three command–line arguments: a username, age, and city. The script should display a personalized message using the provided information. If the city has more than one word, enclose it in quotes.
- Create a Bash script named sh that takes some filenames as command-line arguments. The script should check each file’s existence and display whether it exists or not.
Conclusion
In conclusion, this article has discussed how to use positional parameters in a bash script. Though you can make code as much as you want using the bash parameter, here I have demonstrated two different examples, Hope it will work as a guide to learning the bash language, and don’t forget to explore more. If you have any questions or queries regarding this article, feel free to comment below. Thank You!
People Also Ask
Related Articles
- How to Pass All Parameters in Bash Scripts? [6 Cases]
- Parsing Parameters in Bash Scripts [5 Examples]
- 4 Methods to Pass Named Parameters in a Bash Script
- What is $0 in Bash Script? [4 Practical Examples]
- Difference Between $$ Vs $ in Bash Scripting [With Examples]
- How to Use Alias with Parameters in Bash Scripting? [6 Examples]
- How to Use Bash Function with Parameters? [6 Examples]
<< Go Back to Parameters in Bash Scripting | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners
Hello,
I am currently in the process of learning bash script. If I am wrong let me know, but I think your first example with the arithmetic operations is incorrect. In your switch case statement, bash script automatically uses *) as the final case. This means that the division operation and the final catch all will not work, it will only do addition and subtraction. (i.e your first two examples).
In order to get the bash script to run correctly, I needed to turn off blobbing with -o and instead of having *) I needed to change it to “*”) .This allowed multiplication to work. Again thankyou for your examples.
Steve
Thank you for bringing the loophole to my attention. Indeed, the problem is all about using the asterisk sign since it holds a built-in operation in case statements.
To solve it, your proposition is a good way to go. However, I have run the code by turning off the globbing with
set -o noglob
command but did not get results for the division operation. Can you enlighten me a bit more about how you dealt with it?My two cents on this will be to either avoid using operator syntax in the command line entirely or put multiplication case in the last statement. For my second proposition, enclose the asterisk sign with a double quote whenever it is given to a positional argument. For instance, if we run the code for multiplication, the command will be
./arithmetic_parameters 45 5 "*"
. And the modified code is as given below:#!/bin/bash
# Check if at least 3 positional parameters are provided
if [ $# -lt 3 ]; then
echo "Usage: $0 <num1> <num2> <operator>"
exit 1
fi
num1=$1
num2=$2
operator=$3
result=0
case $operator in
+) result=$((num1 + num2)); operation="addition" ;;
-) result=$((num1 - num2)); operation="subtraction" ;;
/)
if [ $num2 -eq 0 ]; then
echo "Error: Division by zero is not allowed."
exit 1
fi
result=$((num1 / num2))
operation="division"
;;
*)
result=$((num1 * num2))
operation="multiplication"
;;
esac
echo "Performing $operation: $num1 $operator $num2 = $result"
And the output for all arithmetic operations will now look like this: