How to Pass all Arguments in Bash Scripting | Bash Scripting (2024)

Bash arguments are one of the ways users provide inputs to the executing scripts. Using bash arguments, we create reusable scripts avoiding redundant code.

In this guide, we learn various approaches to passing all arguments in bash scripting.

Bash Pass all Arguments

Bash arguments are specified through the command-line after the script name. In the script to get the actual argument that was passed we use the dollar ($) sign, the syntax is $n, where n is an integer between 0 and 9. $0 is reserved for the script name, to get all bash arguments, we use either $@ or $*.

The $@ variable

In bash scripting, $@ represents the position of arguments, starting from one. For instance, when calling our arguments.sh script, we passed 4 and 7. Therefore, $@ will be equal to 4 7.

$@ is used to get all arguments individually quoted as “$1”, “$2”, ”$3”… The following bash script gets all arguments using $@ syntax.

#!/bin/bash# script name: arguments.sh # this is the script nameecho "getting the script name."ARG0=$0echo "\$0 is $ARG0"ARG1=$1ARG2=$2let SUM=$ARG1+$ARG2echo "showing the sum"echo "$ARG1 + $ARG2 = $SUM" echoecho "getting all arguments using \$@"echo "$@"

The output shows two arguments 4 and 7 that were passed via the script. In our script, we assume the arguments are numbers and we calculate the sum. In our example, the sum of 4 and 7 is 11 as shown, and $@ is 4 7.

The $* variable

When we want to store all bash arguments as a single string, we use $*. For instance, in our arguments.sh script above, $* will be equal to “4 7”.

$* gets all arguments as one string, that is, “$1 $2 $3…”. The separator is defined using the first character in $IFS (internal file separator). For instance, if IFS=”-=,#”, the separator will be “-”.

To check the IFS characters defined in your operating system, run the following command:

In our operating system, the first item, the separator, is an empty space (“ “) as shown in the above screenshot. We can change this by setting IFS to what we desire.

In our sample script below, we change the IFS to “-” and the output is concatenated by a “-”.

#!/bin/bash# script name: all-arguments.sh first_name=$1last_name=$2email=$3profession=$4address=$5 # print "$*"echo "showing vars using \$*"echo "value for \$IFS: $(set | grep ^IFS)"IFS="-"echo "$*"

In the above screenshot, we set the first item of IFS to an hyphen(“-”). The output is concatenated with an hyphen when we use $* to process the arguments.

The following script shows the difference between $* and $@. For $* we can set a field separator using IFS.

#!/bin/bash# script name: different.sh # setting the IFS operatorIFS="-"echo "all arguments using \$@"echo "$@"echo "all arguments using \$*"echo "$*"

The screenshot above shows the difference between the $* and $@.

Examples

1. Bash Pass all Arguments as String

In bash script, to pass all arguments as string we use $*. As discussed earlier, we can set the IFS depending on our specific use case. The following script shows an example of passing all arguments as a string.

#!/bin/bash# script name: args-as-string.sh # we use $* to getecho "processing all args as string."echo "$*"

The output screenshot returns all arguments as a string using $*.

2. Read all Arguments using Loop

To read all bash arguments, we use loops. In this section, we are going to demonstrate reading all bash arguments using while and for loops.

$* with loop

The following scripts uses a for loop with “$*” to get all arguments as one string.

#!/bin/bash# script name: all-args.sh for val in "$*"; do echo "value: $val"done

The above script using a for-loop outputs the result as a one string.

$@ with loop

Now, with the same script, we use a while loop to read all arguments. The same construct will apply for a for loop with “$@”. Let’s dig in:

The following script uses a while loop:

#!/bin/bash# script name: all-args.sh counter=1while (( "$#" )); do echo "$1" shift ((counter++))done

Here is the output of the above script:

We will now use a for-loop to obtain the same result as above.

#!/bin/bash# script name: all-args.sh for el in "$@"; do echo "$el"done

The output of the above script is the same as for the while loop. It is as follows:

The for loop gives the same output as the while loop with a counter and a shift operator. It prints each element one by one.

3. Using the shift command

The shift operator shifts the current positional parameters ‘c’ times towards the left and the current positional parameter is assigned the value of the parameter ‘c’ places ahead of it.

If ‘c’ is not specified, it is left shifted by 1.

Assuming there is a script accepting 10 arguments, a shift 4 will result in the following:

  • Older $1, $2 and $3 are discarded.

  • Older $4 becomes $1

  • Older $5 becomes $2

  • Older $5 becomes $3

  • Older $10 becomes $7

Here’s the syntax:

shift c

Shift command takes just one non-negative optional argument ‘c’ which determines the number of positions the parameters should be left shifted. If c is passed as 0, no parameters are shifted. c has a default value of 1.

#!/bin/bashecho "Current values of parameter 1 and 2: " $1 and $2shiftecho "After 1 shift: " $1 and $2shift 3echo "After 3 more shifts: " $1 and $2

Run the script as follows:

./shiftScript.sh 1 2 3 4 5 6 7 8 9

In the above example, $1 holds the value 1 and $2 holds 2. A single shift results in $1 holding the value 2 and $2 having a value of 3. Another 3 shifts makes $1 and $2 have a value of 5 and 6 respectively.

4. Bash Pass all Arguments as Array

An array is a sequence of characters or strings. We use $@ to get an array of arguments passed in, then we process them using a loop. This is useful when we want to perform a repetitive task on the provided input.

To process arrays in bash scripts, we use the following syntax.

#!/bin/bash# script name: arrays.sh # arrayARGS=$@ for arg in $ARGS; do echo "$arg"done

The output is as follows:

We use a for loop to process the passed in arguments as an array.

5. Read all arguments after the nth position

We are going to use the concept of extracting a substring from the main string. The substring will be taken from the nth position till the length of the string.

Here’s the syntax:

${var:offset:length}

Here,

  • The string is stored in the variable var

  • Offset is the position from where to start the string extraction.

  • Length is the number of characters to be extracted from the offset.

#!/bin/bashargs=($@) # Storing the command line arguments in a bash arrayecho "arguments are" ${args[@]} count=$(echo "$#") # Storing the number of command line argumentscount2=${#args[@]} # Storing the length of the arrayecho "count of arguments is" $countecho "length of the array is also" $count2 ind3_1=${args[@]:3:$count}ind3_2=${args[@]:3:$count2}echo "Extracting from third index using count1: " $ind3_1echo "Extracting from third index using count2: " $ind3_2

Run the script as follows:

./positionalScript.sh 1 2 3 4 5 6 7 8 9

The first step is to gather all the command line arguments in a bash array ‘args’. After that, we are counting the length of this array or the number of command line arguments passed to the script. Once we have these two ready, we are able to extract the parameters from the nth position just like we extract substrings from strings in bash.

6. Bash All Arguments to use Arithmetic

The first argument is $0. Using $@ and $* gives us all arguments after the first. The arguments passed can be of any type, that is, integer or string. Therefore, as programmers, we must ensure to process and parse the arguments correctly.

For instance, to calculate the sum of three integers, we get arguments and calculate the sum. The following script illustrates this.

#!/bin/bash# script name: three-sum.sh # define the sumfor el in $@; do let SUM+=$eldoneecho "the sum of $@ is: $SUM"

The output is as follows:

The above screenshot processes arguments after the first argument, the script name. The arguments we get are 3, 4, and 7. The script calculates the sum.

Conclusion

In this guide, we have demonstrated various ways to pass all arguments in bash with examples.

Another convenient way to handle command-line arguments is by using getopts which allows the script to specify which options are valid and what arguments they take.

How to Pass all Arguments in Bash Scripting | Bash Scripting (2024)

References

Top Articles
Narrative Circuits of New World Copper | Mining Language: Racial Thinking, Indigenous Knowledge, and Colonial Metallurgy in the Early Modern Iberian World | North Carolina Scholarship Online
2011 Toyota Tacoma 4x4 Access Cab for sale - Phoenix, AZ - craigslist
Artem The Gambler
Blorg Body Pillow
122242843 Routing Number BANK OF THE WEST CA - Wise
Lamb Funeral Home Obituaries Columbus Ga
Asian Feels Login
Mr Tire Prince Frederick Md 20678
Es.cvs.com/Otchs/Devoted
Free Robux Without Downloading Apps
Stream UFC Videos on Watch ESPN - ESPN
Epaper Pudari
Jessica Renee Johnson Update 2023
Hillside Funeral Home Washington Nc Obituaries
Keniakoop
United Dual Complete Providers
Games Like Mythic Manor
Q Management Inc
Skyward Login Jennings County
Costco Gas Foster City
Tvtv.us Duluth Mn
Equibase | International Results
Divina Rapsing
Exterior insulation details for a laminated timber gothic arch cabin - GreenBuildingAdvisor
Pecos Valley Sunland Park Menu
Mineral Wells Skyward
Accuradio Unblocked
Xxn Abbreviation List 2023
Gopher Hockey Forum
Will there be a The Tower season 4? Latest news and speculation
Where to eat: the 50 best restaurants in Freiburg im Breisgau
In hunt for cartel hitmen, Texas Ranger's biggest obstacle may be the border itself (2024)
Tripcheck Oregon Map
Barbie Showtimes Near Lucas Cinemas Albertville
Daily Journal Obituary Kankakee
Sinai Sdn 2023
The best Verizon phones for 2024
Enjoy4Fun Uno
Heelyqutii
Evil Dead Rise (2023) | Film, Trailer, Kritik
Leena Snoubar Net Worth
Postgraduate | Student Recruitment
Nid Lcms
Sun Tracker Pontoon Wiring Diagram
Frigidaire Fdsh450Laf Installation Manual
Thotsbook Com
Grand Valley State University Library Hours
Penny Paws San Antonio Photos
Cleveland Save 25% - Lighthouse Immersive Studios | Buy Tickets
Automatic Vehicle Accident Detection and Messageing System – IJERT
Myhrkohls.con
Access One Ummc
Latest Posts
Article information

Author: Otha Schamberger

Last Updated:

Views: 5629

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Otha Schamberger

Birthday: 1999-08-15

Address: Suite 490 606 Hammes Ferry, Carterhaven, IL 62290

Phone: +8557035444877

Job: Forward IT Agent

Hobby: Fishing, Flying, Jewelry making, Digital arts, Sand art, Parkour, tabletop games

Introduction: My name is Otha Schamberger, I am a vast, good, healthy, cheerful, energetic, gorgeous, magnificent person who loves writing and wants to share my knowledge and understanding with you.