How to Use First Argument in Bash Script [5 Cases] - LinuxSimply (2024)

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

In Bash, $1 represents the first argument of a script. This means when users provide the first argument while executing a script, it is accessible within the script by the first positional parameter ($1). In this article, primarily I will show how to provide and access the first argument. Moreover, I will try to satiate users’ various other queries related to the first argument in Bash.

Files of First Argument in Bash

Table of Contents

How to Provide the First Argument in Shell Script?

To provide the first argument in a shell script, simply pass it as a command line argument while executing the script. For instance, if you have a script named “myscript.sh” and want to provide “Linux” as the first argument, then execute the script as follows:

./myscript.sh Linux

How to Access the First Argument in Bash Script?

To access the first argument in Bash script, use the first positional parameter $1. Here is a simple example:

#!/bin/bash# Print the first argumentecho "First argument: $1"

EXPLANATION

This Bash script prints out the first argument passed to it. It uses the echo command to display the text “First argument: ” followed by the value of $1, which represents the first argument provided to the script.

How to Use First Argument in Bash Script [5 Cases] - LinuxSimply (2)Executing the script with the argument “Linux” shows the argument after the text “First Argument: ”. Within the script, $1 successfully refers to the first argument of the script.

5 Cases of Handling First Argument in Bash Script

Bash users often need to check the existence of the first argument in a script. Moreover, it is required to modify or skip the first argument occasionally. Therefore, handling the first argument effectively is an essential skill. The following discussion will highlight a few cases for effectively managing the first argument.

1. How to Check the Existence of the First Argument in Bash

To check the existence of the first argument, compare whether the first argument ($1) is empty or not. Use an if statement with -z test operator for this purpose. Here’s an example:

#!/bin/bashif [ -z "$1" ]; then echo "First argument doesn’t exist or it’s empty."else echo "First argument exists and its value is: $1"fi

EXPLANATION

The if statement checks the length of the first argument ($1) using the -z operator. If the length is zero, it indicates that the first argument doesn’t exist or is empty. On the other hand, a non-zero length of the first argument implies that the first argument exists.

How to Use First Argument in Bash Script [5 Cases] - LinuxSimply (3)When the empty string "" or no argument is provided to the script it shows that “First argument doesn’t exist or it’s empty”. However, when the argument “a” is parsed it displays that the first argument exists.

2. How to Pass a File as the First Input Argument in Bash

Provide the file’s path as the first argument when running the script to pass a file as an input argument in a Bash script. Consider a file arg1.txt that contains some data:

#UsersKennyAnitaSmithMohammad

Now, write the following script that uses a while loop to process each line of the arg1.txt file after receiving it as the first argument:

#!/bin/bashfile="$1"arr1=()# Skip the first line and read the rest of the filewhile read arg; do arr1+=("$arg")done < <(tail -n +2 "$file")# Print the elements of arr1echo "${arr1[@]}"

EXPLANATION

This Bash script reads the contents of a file specified as the first argument, excluding the first line. It then populates an array, arr1, with each line from the file. The script achieves this by using process substitution <() to provide the output of tail -n +2 "$file" (which skips the first line of the file) as input to a while loop.

Within the loop, each line is read and appended to the “arr1” array using the += operator. Finally, the script prints all elements of the “arr1” array using "${arr1[@]}".

How to Use First Argument in Bash Script [5 Cases] - LinuxSimply (4)Once executed the script prints the users listed in the “arg1.txt” file in an array by taking the file as the first argument.

3. Iterate Over Input Arguments Except First One

To iterate over input arguments except the first one in a Bash script, use a loop starting from the second argument onwards. The “$@” variable holds all the command line arguments. Looping over “${@:2}” allows you to access each argument individually, starting from the second argument($2). Here is an example:

#!/bin/bashfor i in "${@:2}"do echo "$i"done

EXPLANATION

This Bash script utilizes a for loop to iterate over all arguments passed to the script except for the first one. The loop iterates over the positional parameters starting from the second one using "${@:2}". For each iteration, it echoes the current argument ($i). Essentially, this script prints out all arguments passed to the script, excluding the first one.

How to Use First Argument in Bash Script [5 Cases] - LinuxSimply (5)Once the script is executed it iterates over all the command line arguments except the first one. Therefore, among the three arguments 1, 4 and 5 the script prints the second and third arguments.

4. Change the First Argument in Bash Script

Use the set command to change the first argument in a Bash script. Rewriting the arguments after set – –, reset the command line arguments. The script below demonstrates how set built-in is used to modify the first command line argument:

#!/bin/bash# Update the arguments as requiredset -- "5" "${@:2}"# Display the updated argumentsecho "Updated arguments: $@"

EXPLANATION

This Bash script updates its first argument by replacing it with “5” while keeping the rest unchanged. "${@:2}" in the set command denotes all arguments except the first one. Finally, the script accesses the special variable $@ to show all the command line arguments including the modified first argument.

How to Use First Argument in Bash Script [5 Cases] - LinuxSimply (6)Running the script with arguments “Null”, 7 and 13 changes the first argument “Null” to 5.

5. How to Skip the First Argument in Bash Script

Sometimes users want to get rid of the first argument passed to a Bash script. To skip the first argument, use the shift command to shift all the positional parameters to the left by one. Here’s how you can do it:

#!/bin/bash# Skip the first argumentshift# Now $1 refers to the second argumentecho "Second argument: $1"# Loop through all remaining argumentsecho "Remaining arguments: $@"

EXPLANATION

The script uses shift to skip the first positional argument passed to the script. Therefore, the second positional argument becomes the first argument and can be accessed using $1. Finally, it also prints all the arguments using $@, which represents all arguments passed to the script except the first one, as the first one has been shifted out.

How to Use First Argument in Bash Script [5 Cases] - LinuxSimply (7)Here, the script is executed with arguments 4,5 and 6. Due to the use of shift, all the arguments are shifted to the left by one position. As a result, the second argument becomes accessible by the first positional parameter ($1). Therefore, $@ prints 5 and 6 effectively skipping the first argument(4) provided to the script.

Conclusion

In conclusion, handling the first argument in Bash script is quite easy once you are familiar with the idea of positional parameters. The first positional parameter ($1) is used to access the first argument passed to a script. Moreover, the set built-in and shift command allows users to change or skip the first argument of a Bash script. I hope this article has helped you manipulate the first argument of your script.

People Also Ask

How to check if the first argument is empty?

To check whether the first argument is empty or not use the operators such -n or -z with the test command in an if statement. if [ -n "$1" ] holds true if the length of the first argument is nonzero. On the other hand, if [ -z "$1" ] is true if the length of the first argument is 0.

What is the difference between $1 and $@?

Though both $1 and $@ are used to represent command line arguments, they don’t refer to the same set of arguments. $1 is used to access the first positional parameter whereas $@ expands to all the command line arguments. One can say, “$@” is equivalent to “$1” “$2” “$3″…up to the last argument.

How to store the first argument in a variable in Bash script?

Assign $1 as the value of a variable to store the first argument in a variable within a Bash script. For instance:

#!/bin/bash# Store the first argument in a variablearg1=$1

Here, variable arg1 contains the value of the first argument provided to the script.

Why is $1 in a function not printing the script’s first argument?

$1 in a function can’t print a script’s first argument. Arguments provided to a script are accessible using positional parameters only within the main level of the script not in a function body written in the script. A function can take its own set of arguments independent of the parent script containing the function. So, a function written in a script can access arguments that are provided to the function while calling the function within the script.

#!/bin/bash

# Store the first argument in a variablearg1=$1

Here, variable arg1 contains the value of the first argument provided to the script." } },{ "@type": "Question", "name": "Why is $1 in a function not printing the script's first argument?", "acceptedAnswer": { "@type": "Answer", "text": "$1 in a function can’t print a script’s first argument. Arguments provided to a script are accessible using positional parameters only within the main level of the script not in a function body written in the script. A function can take its own set of arguments independent of the parent script containing the function. So, a function written in a script can access arguments that are provided to the function while calling the function within the script." } }]}

Related Articles

  • How to Check Number of Arguments in Bash? [3 Methods]
  • How to Get Argument in Bash? [4 Methods]
  • How to Pass Arguments to Bash Script? [5 Methods]
  • How to Parse Optional Arguments in Bash Script [2 Ways]
  • How to Pass Array as an Argument in Bash Function? [3 Ways]
  • How to Set Default Argument in Bash [2 Methods]
  • How to Use OPTARG in Bash [3 Practical Examples]
  • How to Use “getopts” in Bash [Complete Guide]
  • [Solved] “bash: Argument list too long” Error

<< Go Back to Argument in Bash Script | Bash Functions | Bash Scripting Tutorial

Rate this post

How to Use First Argument in Bash Script [5 Cases] - LinuxSimply (2024)

References

Top Articles
EARLY BIRD SAVINGS! Italy, France & Spain from Barcelona, Norwegian Cruise Line, 28th March 2025 – Planet Cruise
Closest Mcdonald's Restaurant To My Location
3 Tick Granite Osrs
Play FETCH GAMES for Free!
Bild Poster Ikea
My Arkansas Copa
Thor Majestic 23A Floor Plan
Tyson Employee Paperless
Sandrail Options and Accessories
How Many Cc's Is A 96 Cubic Inch Engine
Mr Tire Prince Frederick Md 20678
Pitt Authorized User
craigslist: south coast jobs, apartments, for sale, services, community, and events
Craigslist - Pets for Sale or Adoption in Zeeland, MI
Bme Flowchart Psu
อพาร์ทเมนต์ 2 ห้องนอนในเกาะโคเปนเฮเกน
All Buttons In Blox Fruits
Conan Exiles Colored Crystal
Walmart Double Point Days 2022
Beebe Portal Athena
Aldi Süd Prospekt ᐅ Aktuelle Angebote online blättern
Xomissmandi
Imagetrend Inc, 20855 Kensington Blvd, Lakeville, MN 55044, US - MapQuest
Csi Tv Series Wiki
Craigslist Mt Pleasant Sc
Yog-Sothoth
Garnish For Shrimp Taco Nyt
Kingdom Tattoo Ithaca Mi
Redfin Skagit County
Mini Handy 2024: Die besten Mini Smartphones | Purdroid.de
48 Oz Equals How Many Quarts
Babbychula
Craigslist In Myrtle Beach
Andhra Jyothi Telugu News Paper
Natashas Bedroom - Slave Commands
Gpa Calculator Georgia Tech
Ferguson Employee Pipeline
Download Diablo 2 From Blizzard
Anderson Tribute Center Hood River
FREE - Divitarot.com - Tarot Denis Lapierre - Free divinatory tarot - Your divinatory tarot - Your future according to the cards! - Official website of Denis Lapierre - LIVE TAROT - Online Free Tarot cards reading - TAROT - Your free online latin tarot re
Wilson Tire And Auto Service Gambrills Photos
Academic Calendar / Academics / Home
Nu Carnival Scenes
Az Unblocked Games: Complete with ease | airSlate SignNow
Ferhnvi
Amateur Lesbian Spanking
Craigslist Pet Phoenix
Amourdelavie
Festival Gas Rewards Log In
How to Choose Where to Study Abroad
Wayward Carbuncle Location
Latest Posts
Article information

Author: Arielle Torp

Last Updated:

Views: 5681

Rating: 4 / 5 (61 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Arielle Torp

Birthday: 1997-09-20

Address: 87313 Erdman Vista, North Dustinborough, WA 37563

Phone: +97216742823598

Job: Central Technology Officer

Hobby: Taekwondo, Macrame, Foreign language learning, Kite flying, Cooking, Skiing, Computer programming

Introduction: My name is Arielle Torp, I am a comfortable, kind, zealous, lovely, jolly, colorful, adventurous person who loves writing and wants to share my knowledge and understanding with you.