How to get the second last argument from a shell script?

I want to get the second last item given to the shell program. I am currently doing it like this:

file1_tmp="${@: -2}"
oldIFS=$IFS
IFS=" "
count=0
for value in $file1; do
  if [[ count -e 0 ]]; then
    file1=$value
  fi
    count=1
done
oldIFS=$IFS 

I am sure there is a much easier way to do this. So, how can I get the second last argument from shell script input as few lines as possible?

+6
source share
4 answers
set -- "first argument" "second argument" \
       "third argument" "fourth argument" \
       "fifth argument"
second_to_last="${@:(-2):1}"
echo "$second_to_last"

Pay attention to the quote, which guarantees that the arguments coincide with a space - which your original solution does not do.

+16
source

In bash / ksh / zsh you can just ${@: -2:1}

$ set a b c d 
$ echo ${@: -1:1}
c

On POSIX sh, you can use eval:

$ set a b c d 
$ echo $(eval "echo \$$(($#-2))")
c
+4
source
n=$(($#-1))
second_to_last=${!n}
echo "$second_to_last"
+2

bash:

$ set -- aa bb cc dd ee ff
$ echo "${@: -2:1}   ${@:(-2):1}   ${@:(~1):1}   ${@:~1:1}   ${@:$#-1:1}"
ee   ee   ee   ee   ee

(~) ( ).
.

() :

$ a=1  ; b=-a; echo "${@:b-1:1}   ${@:(b-1):1}   ${@:(~a):1}   ${@:~a:1}   ${@:$#-a:1}"
ee   ee   ee   ee   ee

$ a=2  ; b=-a; echo "${@:b-1:1}   ${@:(b-1):1}   ${@:(~a):1}   ${@:~a:1}   ${@:$#-a:1}"
dd   dd   dd   dd   dd

For really old shells you should use eval:

eval "printf \"%s\n\" \"\$$(($#-1))\""
0
source

All Articles