One For The Gods Of Linux [ Bash Scripting postional parameters / arguments ]
Good evening
I am in the process of trying to get my head around BASH scripting I am not a programmer and am having trouble with understanding Positional parameters and arguments.
I understand how to declare variables but am failing to understand the concept of arguments and positional parameters.
$0, $1, $2
From my understanding $0 holds the script name?
Could somebody write a noob script example breaking it down and explaining arguments it would really help me out i'm getting nothing but headaches lol
Many Thanks
Appreciate it
I am in the process of trying to get my head around BASH scripting I am not a programmer and am having trouble with understanding Positional parameters and arguments.
I understand how to declare variables but am failing to understand the concept of arguments and positional parameters.
$0, $1, $2
From my understanding $0 holds the script name?
Could somebody write a noob script example breaking it down and explaining arguments it would really help me out i'm getting nothing but headaches lol
Many Thanks
Appreciate it
Microsoft's strategy to conquer the I.T industry
" Embrace, evolve, extinguish "
" Embrace, evolve, extinguish "
Comments
-
NightShade03 Member Posts: 1,383 ■■■■■■■□□□Here is a quick low down on this:
$0 is the script name as you mentioned
$1 is the first argument
$2 is the second argument
So on and so forth...
What you also need are these two:
a special variable that holds then entire list
$# the total numerical value of all arguments
For example a BASH script called test:
#!/bin/bash
echo $#
echo $0
echo $1
echo $2
On the command line:
# ./test hello
hello
1
./test
hello
<- this is a blank line
# ./test hello world
hello world
2
./test
hello
world
Obviously you don't want to guess how many arguments a script will have when the user executes it so you leverage a while loop to filter through each parameter. See this Stackoverflow link for an example (sry to much code to post here):
linux - How to get arguments with flags in bash script - Stack Overflow
Notice how the author checks to ensure that the $# is great than (gt) 0 and if that is true...loop through all parameters.
Hope this makes more sense. -
ally_uk Member Posts: 1,145 ■■■■□□□□□□Many thanks for the explanation I will fire up a terminal and get busyMicrosoft's strategy to conquer the I.T industry
" Embrace, evolve, extinguish "