Get last parameter on shell script
Solution 1
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
Solution 2
For this, you can use:
${@: -1}
Test
$ cat a
#!/bin/bash
echo "passed $# parameters, last being --> ${@: -1}"
$ ./a a b c d
passed 4 parameters, last being --> d
$ ./a a b c d e f g
passed 7 parameters, last being --> g
Solution 3
Quoting a way from here:
for last; do : ; done
echo "${last}"
The last argument passed to the script would be stored in the variable last
.
As mentioned in the link, this would work in POSIX-compatible shells it works for ANY number of arguments.
BTW, I doubt if your script works the way you've written in your question:
var1 = `echo "$#"`
You need to remove those spaces around =
, i.e. say:
var1=`echo "$#"`
or
var1=$(echo "$#")
user2930942
Updated on June 30, 2022Comments
-
user2930942 almost 2 years
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 ?
-
Palec over 9 yearsWhere is the
${!#}
documented? Is this just a Bash feature? Is it in POSIX? -
mcoolive over 8 yearsWith an old Solaris, with the old bourne shell (not POSIX), I have to write "for last in "$@"; do : ; done"
-
mcoolive over 8 yearsIt is specific to Bash. So use it if your shebang in bash. If you need something portable, I found only the loop as suggested by @devnull.
-
cst1992 over 7 yearsThis kind of defeats the purpose. It reminds me of printf in C, but what if we want to do something similar to
test
command? -
chepner over 7 yearsThat's not a great example; POSIX leaves the result of a test command specified if there are more than 4 arguments.