Get last parameter on shell script

11,469

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 "$#")
Share:
11,469
user2930942
Author by

user2930942

Updated on June 30, 2022

Comments

  • user2930942
    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
    Palec over 9 years
    Where is the ${!#} documented? Is this just a Bash feature? Is it in POSIX?
  • mcoolive
    mcoolive over 8 years
    With an old Solaris, with the old bourne shell (not POSIX), I have to write "for last in "$@"; do : ; done"
  • mcoolive
    mcoolive over 8 years
    It 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
    cst1992 over 7 years
    This 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
    chepner over 7 years
    That's not a great example; POSIX leaves the result of a test command specified if there are more than 4 arguments.