Bash Beginner Series #3: Passing Arguments to Bash Scripts (2024)

Arguments can be useful, especially with Bash!

So far, you have learned how to use variables to make your bash scripts dynamic and generic, so it is responsive to various data and different user input.

In this tutorial, you will learn how you can pass variables to a bash scripts from the command line.

Passing argument to a bash shell script

The following script count_lines.sh will output the total number of lines that exist in whatever file the user enters:

#!/bin/bashecho -n "Please enter a filename: "read filenamenlines=$(wc -l < $filename)echo "There are $nlines lines in $filename"

For example, the user can enter the file /etc/passwd and the script will spit out the number of lines as a result:

Bash Beginner Series #3: Passing Arguments to Bash Scripts (1)

This script works fine; however, there is a much better alternative!

Instead of prompting the user for the filename, we can make the user simply pass the filename as a command line argument while running the script as follows:

./count_lines.sh /etc/passwd

The first bash argument (also known as a positional parameter) can be accessed within your bash script using the $1 variable.

So in the count_lines.sh script, you can replace the filename variable with $1 as follows:

#!/bin/bashnlines=$(wc -l < $1)echo "There are $nlines lines in $1"

Notice that I also got rid of the read and first echo command as they are no longer needed!

Finally, you can run the script and pass any file as an argument:

./count_lines.sh /etc/groupThere are 73 lines in /etc/group

Passing multiple arguments to a bash shell script

You can pass more than one argument to your bash script. In general, here is the syntax of passing multiple arguments to any bash script:

script.sh arg1 arg2 arg3 …

The second argument will be referenced by the $2 variable, the third argument is referenced by $3, .. etc.

The $0 variable contains the name of your bash script in case you were wondering!

Now we can edit our count_lines.sh bash script so that it can count the lines of more than one file:

#!/bin/bashn1=$(wc -l < $1)n2=$(wc -l < $2)n3=$(wc -l < $3)echo "There are $n1 lines in $1"echo "There are $n2 lines in $2"echo "There are $n3 lines in $3"

You can now run the script and pass three files as arguments to the bash script:

Bash Beginner Series #3: Passing Arguments to Bash Scripts (2)

As you can see, the script outputs the number of lines of each of the three files; and needless to say that the ordering of the arguments matters, of course.

Getting creative with arguments in Bash shell

There are a whole lot of Linux commands out there.

Some of them are a bit complicated as they may have long syntax or a long array of options that you can use.

Fortunately, you can use bash arguments to turn a hard command into a pretty easy task!

To demonstrate, take a look at the following find.sh bash script:

#!/bin/bashfind / -iname $1 2> /dev/null

It’s a very simple script that yet can prove very useful! You can supply any filename as an argument to the script and it will display the location of your file:

Bash Beginner Series #3: Passing Arguments to Bash Scripts (3)

You see how this is now much easier than typing the whole find command! This is a proof that you can use arguments to turn any long complicated command in Linux to a simple bash script.

If you are wondering about the 2> /dev/null, it means that any error message (like file cannot be accessed) won't be displayed on the screen. I suggest reading about stderr redirection in Linux and /dev/null to get more knowledge on this topic.

Bonus Tip: Special variables in Bash shell

Bash has a lot of built-in special variables that are quite handy and are available at your disposal.

The table below highlights the most common special built-in bash variables:

Special VariableDescription
$0The name of the bash script.
$1, $2...$nThe bash script arguments.
$$The process id of the current shell.
$#The total number of arguments passed to the script.
$@The value of all the arguments passed to the script.
$?The exit status of the last executed command.
$!The process id of the last executed command.

To see these special variables in action; take a look at the following variables.sh bash script:

#!/bin/bashecho "Name of the script: $0"echo "Total number of arguments: $#"echo "Values of all the arguments: $@"

You can now pass any arguments you want and run the script:

Bash Beginner Series #3: Passing Arguments to Bash Scripts (6)

Alright, this brings us to the end of this chapter. I hope you now realize how powerful and useful bash arguments can be.

Need some practice, download this PDF and practice passing arguments to bash scripts with simple scripting challenges. Their solutions are also included.

Bash Chapter 3 Practice QuestionsProblems and their solution to practice what you just learned in this chapterBash-Chapter-3-Practice-Questions-Linux-Handbook.pdf30 KBdownload-circle

After that, take a look at the next chapter where I am going to show you can create and utilize arrays in your bash scripts.

Bash Beginner Series #3: Passing Arguments to Bash Scripts (2024)

References

Top Articles
Early Bird: Definition & Bedeutung im Marketing
Nashville Then: Experience 50 years ago in August 1974 through photos
Toa Guide Osrs
Beautiful Scrap Wood Paper Towel Holder
Chase Claypool Pfr
Best Restaurants In Seaside Heights Nj
Citi Card Thomas Rhett Presale
B67 Bus Time
Hardly Antonyms
Lima Crime Stoppers
Blue Beetle Showtimes Near Regal Swamp Fox
Med First James City
Socket Exception Dunkin
Lenscrafters Huebner Oaks
Evil Dead Rise Showtimes Near Regal Columbiana Grande
Lax Arrivals Volaris
Hoe kom ik bij mijn medische gegevens van de huisarts? - HKN Huisartsen
Nba Rotogrinders Starting Lineups
Are They Not Beautiful Wowhead
Ou Class Nav
Katherine Croan Ewald
Video shows two planes collide while taxiing at airport | CNN
1-833-955-4522
Yakimacraigslist
Tamilyogi Proxy
Gia_Divine
Curry Ford Accident Today
Exterior insulation details for a laminated timber gothic arch cabin - GreenBuildingAdvisor
Kamzz Llc
Redfin Skagit County
Mynahealthcare Login
Penn State Service Management
Shnvme Com
PA lawmakers push to restore Medicaid dental benefits for adults
SF bay area cars & trucks "chevrolet 50" - craigslist
Tugboat Information
Captain Billy's Whiz Bang, Vol 1, No. 11, August, 1920&#10;America's Magazine of Wit, Humor and Filosophy
Jack In The Box Menu 2022
Achieving and Maintaining 10% Body Fat
Yale College Confidential 2027
Holzer Athena Portal
The Complete Uber Eats Delivery Driver Guide:
Stoughton Commuter Rail Schedule
CPM Homework Help
Craigslist Charles Town West Virginia
Craigslist Cars And Trucks For Sale By Owner Indianapolis
How To Connect To Rutgers Wifi
The Significance Of The Haitian Revolution Was That It Weegy
Aspen.sprout Forum
Itsleaa
Texas Lottery Daily 4 Winning Numbers
Latest Posts
Article information

Author: Sen. Emmett Berge

Last Updated:

Views: 5679

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Sen. Emmett Berge

Birthday: 1993-06-17

Address: 787 Elvis Divide, Port Brice, OH 24507-6802

Phone: +9779049645255

Job: Senior Healthcare Specialist

Hobby: Cycling, Model building, Kitesurfing, Origami, Lapidary, Dance, Basketball

Introduction: My name is Sen. Emmett Berge, I am a funny, vast, charming, courageous, enthusiastic, jolly, famous person who loves writing and wants to share my knowledge and understanding with you.