1

In my /bin/sh script, I need to pass an indeterminate number of positional parameters, and get the last one (assign the last one to variable $LAST) and then remove this last argument from $@

For example, I call my script with 4 arguments:

./myscript.sh AAA BBB CCC DDD

And inside my script, I need to echo the following:

echo $LAST
DDD

echo $@
AAA BBB CCC

How can I achieve this ?

oguz ismail
  • 1
  • 16
  • 47
  • 69
400 the Cat
  • 266
  • 3
  • 23
  • Does this answer your question? [Getting the last argument passed to a shell script](https://stackoverflow.com/questions/1853946/getting-the-last-argument-passed-to-a-shell-script) – l0b0 Jun 06 '20 at 05:36
  • 1
    @l0b0 - no, it does not. Those solutions only work in bash. – 400 the Cat Jun 06 '20 at 05:50
  • @400theCat, Re *"...only work in bash"*: correction -- **some** of the 28 answers to [*Getting the last argument passed to a shell script*](https://stackoverflow.com/questions/1853946/getting-the-last-argument-passed-to-a-shell-script) are `bash` only, but some of the other answers are for *POSIX* shells. – agc Jun 06 '20 at 06:42
  • @agc However, that question does not ask how to remove the last positional parameter. – oguz ismail Jun 06 '20 at 07:00
  • It would be a lot easier to simply change your script to take `DDD` as the first argument, followed by `AAA`, `BBB`, and `CCC`. – chepner Jun 07 '20 at 22:16

1 Answers1

2

Use a loop to move all arguments except the last to the end of positional parameters list; so that the last becomes the first, could be referred to by $1, and could be removed from the list using shift.

#!/bin/sh -
count=0
until test $((count+=1)) -ge $#
do
  set -- "$@" "$1"
  shift
done

LAST=${1-}
shift $((!!$#))

echo "$LAST"
echo "$@"
oguz ismail
  • 1
  • 16
  • 47
  • 69