How To Pass and Parse Linux Bash Script Arguments and Parameters - GeeksforGeeks (2024)

Parsing and Passing of Arguments into bash scripts/ shell scripts is quite similar to the way in which we pass arguments to the functions inside Bash scripts. We’ll see the actual process of passing on the arguments to a script and also look at the way to access those arguments inside the script.

Passing arguments before running

We can pass parameters just after the name of the script while running the bash interpreter command. You can pass parameters or arguments to the file. Just the command for running the script normally by adding the value of the parameters directly to the script. Every parameter is a space-separated value to pass to the shell script.

bash scriptname.sh 

The above command will just run the script without passing the parameters.

Whereas the command below will pass the arguments to the script.

bash scriptname.sh parameter1 parameter2 parameter3 nth-parameter

How To Pass and Parse Linux Bash Script Arguments and Parameters - GeeksforGeeks (1)

Running bash script with passing parameters

The above screenshot displays the parameters passed to the script, how we’ll do that, which we’ll explain in the next section. But right now we can see we have passed in the parameters from outside of the script using bash environment variables. You can even use strings and other data types but beware of any whitespace. White space will make the variable a separate parameter. So, for strings especially, be careful to strictly surround them with quotation marks.

Detecting Command Line Arguments

Now, we’ll see how we access those parameters inside of the script. We’ll use the number of the parameters passed in the order i.e for the first parameters passed, we’ll parse(access) the parameter by using $1 as the variable. The first parameter is stored in the $1 variable. Furthermore, you can assign this variable to any other user-defined variable you like. For the nth parameter passed, you can use $n to access that particular parameter. Here, the variable name starts with 1 because the filename/ script name is the 0th parameter. If you have more than 9 parameters, make sure to use { } around the number as without the parenthesis, bash will only see $10 as $1 and exclude the 0, so use ${10} and so on instead of simply $10.

#!/bin/bashecho "1st parameter = $1 "echo "2nd Parameter = $2 "

The above script can access the parameters from the command line/ shell using the positional parameters, which are 1, 2, 3, and so on.

How To Pass and Parse Linux Bash Script Arguments and Parameters - GeeksforGeeks (2)

Accessing the arguments from the script.

As you can see, we have used {} to access the parameter variable numbers from 10 onwards. The script can be used for loops and while loops to iterate over the parameters, but we will discuss it in further sections.

Assign Provided Arguments To Bash Variable

We can also assign it to other custom variables to make the script more dynamic and mold it according to the needs. Though the above script when run will only print two parameters, surely you can access more parameters using the variable as the order of parameters in numbers. The script can access the positional variables from the command line and use them in the required places wherever needed within the script.

#!/bin/basha=$1b=$2p=$(($a*$b))echo "The product of $a and $b = $p"

How To Pass and Parse Linux Bash Script Arguments and Parameters - GeeksforGeeks (3)

Assign Provided Arguments To Bash Variable

The above script accesses the positional parameters i.e $1 and $2 passed into the script and stores the user-defined variables to access them later and modify them accordingly. We can also access more parameters using iterative methods as we’ll see in the upcoming sections.

We also have the ability to check for any NULL or empty parameters passed using the -z or -n flags. From this, we can verify whether the parameters were passed or not.

#!/bin/bashif [[ -z $1 ]];then echo "No parameter passed."else echo "Parameter passed = $1"fi

How To Pass and Parse Linux Bash Script Arguments and Parameters - GeeksforGeeks (4)

Checking for positional parameters passed in or not.

With this script, we can detect whether any positional parameters were passed in or nothing was passed. The -z flag checks for any NULL or uninitialized variables in BASH. The -z flag returns true if the variable passed is NULL or uninitialized. Hence, we can make use of basic If-else statements to detect the parameters passed.

We can also use -n flag which returns true if no parameters are passed, so we have to make use of ! to reverse the condition.

Such as follows:

#!/bin/bashif [[ ! -n $1 ]];then echo "No parameter passed."else echo "Parameter passed = $1"fi

This script will also give the same output as well, but we are making use of -n flag instead of -z.

Reading Multiple Arguments with For or While loop

We can use “@” variable to access every parameter passed to the script via the command line. It is a special variable that holds the array of variables in BASH. In this case, we are using it alone, so it contains the array of positional parameters passed in. We can use it to iterate over the parameters passed using loops or while loop as well.

#!/bin/bashfor i in $@do echo -e "$i\n"done

How To Pass and Parse Linux Bash Script Arguments and Parameters - GeeksforGeeks (5)

Using loops and @ variable to access the parameters as array elements.

We used a range-based for loop to iterate over till there are elements in the @ array. We simply iterate over the array and print the element. We can simply assign it, modify the values, and make the required changes to the parameters and arguments to achieve the desired outcome from the script.

OR

We can also print the arguments using the while loop and the environmental variables of BASH.

#!/bin/bashi=$(($#-1))while [ $i -ge 0 ];do echo ${BASH_ARGV[$i]} i=$((i-1))done

How To Pass and Parse Linux Bash Script Arguments and Parameters - GeeksforGeeks (6)

Using while loop to iterate over the passed parameters.

We are using the variable ‘#‘ as it holds the number of parameters passed in. We initialize the number of parameters and take away one as we are going to use an array to iterate over it. So, as usual, the array’s index starts from 0. As this array is initialized from the last element or parameter passed, we need to decrement the counter until 0 to print every parameter in the order it is passed. We simply use the BASH_ARGV array to access the parameters and print its value. Also, at every iteration, we decrease the value of i- the iterator or counter by one using the arithmetic double braces. From this, we simply print every parameter passed to the script using a while loop as shown from the output screenshot.

Reading With Parameter Names

Using getopts to parse arguments and parameters

We can use the getopts program/ command to parse the arguments passed to the script in the command line/ terminal by using loops and switch-case statements.

#!/bin/bashwhile getopts n:c: optiondo case "${option}" in n)nation=${OPTARG};; c)code=${OPTARG};; esacdoneecho "Nation : $nation"echo "code : $code"

How To Pass and Parse Linux Bash Script Arguments and Parameters - GeeksforGeeks (7)

Using getopts to parse arguments and parameters

Using getopts, we can assign the positional arguments/ parameters from the command line to the bash variables directly. This allows us to manage the parameters nicely and in a systematic way. In the above script, we have used two arguments to store the bash variables using the getopts syntax, while loops and switch-case statements.

Printing Values of All Arguments

We can print the arguments passed to the script by a simple powerful variable ‘@’ which stores all the parameters passed.

#!/bin/bashecho "The arguments passed in are : $@"

How To Pass and Parse Linux Bash Script Arguments and Parameters - GeeksforGeeks (8)

Printing Values of All Arguments

Accessing the number of Parameters passed

We can also use the variable ‘#’ to access the number of parameters passed from the command line. The # variable basically contains the number of parameters/ arguments which are passed into the script.

#!/bin/bashecho "The number of arguments passed in are : $#"

How To Pass and Parse Linux Bash Script Arguments and Parameters - GeeksforGeeks (9)

Accessing the number of Parameters passed

The following were the process and specification of passing and parsing the variables in the bash script. The logic of shifting and making modifications to the variables is in the hands of the user. This was just a demonstration of passing in and parsing down the arguments from the command line to the script to make them more dynamic.



M

meetgor

How To Pass and Parse Linux Bash Script Arguments and Parameters - GeeksforGeeks (10)

Improve

Previous Article

Shell Scripting - Functions and it's types

Next Article

Shell Scripting - Standard Input, Output and Error

Please Login to comment...

How To Pass and Parse Linux Bash Script Arguments and Parameters - GeeksforGeeks (2024)

References

Top Articles
Buy Polarizing Filters for Camera Lenses Online | Urth EU
Kc Wolf To The Kansas City Chiefs Crossword Clue
neither of the twins was arrested,传说中的800句记7000词
The UPS Store | Ship & Print Here > 400 West Broadway
Pangphip Application
J & D E-Gitarre 905 HSS Bat Mark Goth Black bei uns günstig einkaufen
Obor Guide Osrs
Crocodile Tears - Quest
Jasmine
Tlc Africa Deaths 2021
Find The Eagle Hunter High To The East
Full Range 10 Bar Selection Box
charleston cars & trucks - by owner - craigslist
Colorado mayor, police respond to Trump's claims that Venezuelan gang is 'taking over'
Dutch Bros San Angelo Tx
"Une héroïne" : les funérailles de Rebecca Cheptegei, athlète olympique immolée par son compagnon | TF1 INFO
Trac Cbna
Is Grande Internet Down In My Area
List of all the Castle's Secret Stars - Super Mario 64 Guide - IGN
Royal Cuts Kentlands
Outlet For The Thames Crossword
*Price Lowered! This weekend ONLY* 2006 VTX1300R, windshield & hard bags, low mi - motorcycles/scooters - by owner -...
Woodmont Place At Palmer Resident Portal
Dtlr Duke St
Shoe Station Store Locator
Hesburgh Library Catalog
Amerisourcebergen Thoughtspot 2023
Healthy Kaiserpermanente Org Sign On
Tracking every 2024 Trade Deadline deal
Uno Fall 2023 Calendar
Craigslist In Myrtle Beach
Mp4Mania.net1
Darrell Waltrip Off Road Center
Sinfuldeeds Vietnamese Rmt
Indiefoxx Deepfake
Craigslist List Albuquerque: Your Ultimate Guide to Buying, Selling, and Finding Everything - First Republic Craigslist
How To Paint Dinos In Ark
Evil Dead Rise (2023) | Film, Trailer, Kritik
Compare Plans and Pricing - MEGA
Frommer's Philadelphia & the Amish Country (2007) (Frommer's Complete) - PDF Free Download
Express Employment Sign In
Mcalister's Deli Warrington Reviews
LoL Lore: Die Story von Caitlyn, dem Sheriff von Piltover
Parent Portal Pat Med
Valls family wants to build a hotel near Versailles Restaurant
Wordle Feb 27 Mashable
56X40X25Cm
Conan Exiles Tiger Cub Best Food
300+ Unique Hair Salon Names 2024
French Linen krijtverf van Annie Sloan
Where and How to Watch Sound of Freedom | Angel Studios
Cognitive Function Test Potomac Falls
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated:

Views: 5687

Rating: 4.3 / 5 (64 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.