Open In App

Shell Script Program to Demonstrate the ‘$#’ Variable

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Linux, if we want to count the total number of arguments that are passed to the specific script then we can use the $#variable. This variable stores the total count of arguments, the program properly tracks and reports the number of arguments passed at the runtime of the script. Along with this, we can also perform different operations on this passed argument at runtime. This enables users to interact with the script and also receive valuable information about the argument count.

Prerequisites:

  1. Linux Environment: This tutorial assumes you are working in a Linux environment. The provided instructions and script are tailored for Linux systems.
  2. Terminal Access: You should have access to a terminal or command-line interface on your Linux system. Most Linux distributions provide this by default.

Example:

Input: 
./variable.sh 10 20 30

Output:
This script will calculate the total number of arguments and their sum.
Arguments passed to the script:
10
20
30
Total number of arguments: 3
Sum of arguments: 60


Here our main task is to write the script which will count the total number of arguments passed by executing the script. Along with this, the script will print the total number of arguments passed, and the list of arguments. Also, the script will count the sum of numbers that are passed as an argument to the script.

Creating the Script

Step 1: Firstly, we will initialize the variable and check the arguments. We have defined the variables as “total_arguments” to count the total number of arguments and “sum” to store the sum of numerous arguments. There is an initial message printed to the user. Then it checks if there are no arguments provided using the special “$#” variable, and if so, it prints a message stating that there is no argument and the script will get excited.

#!/bin/bash
# Initialize variables for total number of arguments and their sum
total_arguments=0
sum=0
echo "This script will calculate the total number of arguments and their sum."

# Check if there are no arguments
if [ $# -eq 0 ]; then
echo "No arguments provided."
exit 1
fi


Step 2: Then we will perform looping through arguments to check whether the arguments are number type. In the loop, we are printing each argument and also checking if it is a number by using the regular expression pattern. If the argument is a number, then we are increasing the “total_arguments” count and then adding the number to the “sum” variable.

# Loop through the provided arguments and print them
echo "Arguments passed to the script:"
for arg in "$@"; do
echo "$arg"
# Check if the argument is a number
if [[ $arg =~ ^[0-9]+$ ]]; then
total_arguments=$((total_arguments + 1))
sum=$((sum + arg))
else
echo "Invalid argument: '$arg' is not a number. Skipping."
fi
done


Step 3: Lastly the script will print the total number of valid numeric arguments counted in the “total_arguments” variable and the sum of the arguments that are stored in the “sum” variable.

echo "Total number of arguments: $total_arguments"
echo "Sum of arguments: $sum"
# End of the script


Steps to create and execute a bash script

Step 1: Open the terminal window using the keyboard shortcut “Ctrl + Alt + T“.

Opening Terminal

Opening Terminal

Step 2: Using any text editor like Vim, vi, or Nano, open a new blank file in the text editor.

nano argsvariable.sh


Creating script file in Nano Editor

Creating script files in Nano Editor

Step 3: Now, we need to write the below script in the created file argsvariable.sh.

#!/bin/bash
# Initialize variables for total number of arguments and their sum
total_arguments=0
sum=0
echo "This script will calculate the total number of arguments and their sum."
# Check if there are no arguments
if [ $# -eq 0 ]; then
echo "No arguments provided."
exit 1
fi
# Loop through the provided arguments and print them
echo "Arguments passed to the script:"
for arg in "$@"; do
echo "$arg"
# Check if the argument is a number
if [[ $arg =~ ^[0-9]+$ ]]; then
total_arguments=$((total_arguments + 1))
sum=$((sum + arg))
else
echo "Invalid argument: '$arg' is not a number. Skipping."
fi
done

echo "Total number of arguments: $total_arguments"
echo "Sum of arguments: $sum"
# End of the script


Writing Script Code

Writing Script Code

Step 4: Now, as we have created the script, we need to make the script executable by running the chmod command in the terminal.

chmod +x argsvariable.sh


Granting Executable Permissions

Granting Executable Permissions

Step 5: Finally we need to execute the script by passing the argument by using the below command:

./argsvariable.sh <<arguments>>


Output:

Script Executed

Script Executed

Explanation:

In the above output, we can see that we have executed the script “./argsvariable.sh 10 20 30” where we have passed the “10 20 30” as an argument to the script. Firstly, the script started by stating the initial message. Then the script prints all the arguments that are provided at runtime of the script. Then the script counts the valid numeric arguments and prints the total number of arguments as “3” by using the variable “$#“. Lastly, the script calculates the sun of the arguments passed in the script and results as “60“.

Conclusion

In conclusion, the shell script demonstrating the use of the $# variable effectively showcases its utility in counting the number of arguments passed to the script. By allowing for user interaction, input validation, and arithmetic operations, this script serves as a practical example of how to process and analyze arguments in shell scripting. It empowers users to provide various inputs and promptly receive essential information about the total argument count and their sum, illustrating the versatility of shell scripts in managing variable quantities of data and performing meaningful calculations.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads