Getting Started With Positional-Parameters And For Loops

Table of contents

In today’s blog, we will discuss positional parameters, how they are used, and demonstrate their functionality using for loops.
Positional Parameters
Positional Parameters are variables that contain the content of the command line i.e. these are the special variables that store values and pass them we run the script. The variable are from $0 to $9 .
$0 → is the script name
$1 → first argument
$2 → second argument
…..
$@ → all arguments separated
$# → total number of arguments
$* → all argument in a string.
$0
→myscript.sh
$1
→Isha
$2
→Bash
$#
→2
$@
→Isha Bash
$*
→Isha Bash
(but treated as one string if unquoted)
To understand how $@ works, let's start with for loops and then use it within a for loop.
For Loops
A FOR loop in Bash allows you to iterate over a list of items. The syntax looks like this:
for VARIABLE in ITEM1 ITEMN
do
command1
command2
done
- Below is the example where item1 is red , item2 is black , item3 is blue.
Below is another example with creation of variable
Now lets see an example using $@ in for loop
$@ (without quotes) — can break arguments that include spaces (like "dragon fruit" will become dragon and fruit).
Repository Link
You can find all the scripts mentioned in this article in the repository below:
https://github.com/ishaj72/Bash-Scripting
Stay tuned for the next article, where we will explore While Loops and Complex Positional Parameter examples in Bash scripting.
Happy reading!!
Subscribe to my newsletter
Read articles from Isha Jain directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Isha Jain
Isha Jain
An enthusiast about continuously broadening my horizons in the dynamic world of technology.