Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last parameter on shell script [duplicate]

case 1 : suppose I am passing a number of parameters to my shell script as follows :

./myshell_script a b c d 

and if I run echo $# will give me number of parameters from command line I have passed and I stored it in a variable like [ since I dont know number of arguments a user is passing ]:

var1 = `echo "$#"`

case 2 : $4 gives me the name of last argument .

if i want it to store in

var2 then

var2 = $4 

My question is :

If I want to store value I get from var1 to var2 directly , how would be it possible in shell script ?

for ex :

./myshell_script.sh a b c

var1 = `echo "$#"` ie var1 = 3

now I want

var2 = c [ ie always last parameter , since I dont know how many number of parameters user is passing from comand line ]

what I have to do ?

like image 443
user2930942 Avatar asked Oct 30 '13 09:10

user2930942


1 Answers

The script below shows how you can get the first and last arguments passed to a script:

numArgs="$#"
echo "Number of args: $numArgs"

firstArg="$1"
echo "First arg: $firstArg"

lastArg="${!#}"
echo "Last arg: $lastArg"

Output:

$ ./myshell_script.sh a b c d e f
Number of args: 6
First arg: a
Last arg: f
like image 169
dogbane Avatar answered Sep 27 '22 18:09

dogbane