3

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 ?

5
  • Does this answer your question? Getting the last argument passed to a shell script
    – l0b0
    Commented Jun 6, 2020 at 5:36
  • 1
    @l0b0 - no, it does not. Those solutions only work in bash. Commented Jun 6, 2020 at 5:50
  • @400theCat, Re "...only work in bash": correction -- some of the 28 answers to Getting the last argument passed to a shell script are bash only, but some of the other answers are for POSIX shells.
    – agc
    Commented Jun 6, 2020 at 6:42
  • @agc However, that question does not ask how to remove the last positional parameter. Commented Jun 6, 2020 at 7: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
    Commented Jun 7, 2020 at 22:16

1 Answer 1

4

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 "$@"
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.