Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign last positional parameter to variable and remove it from "$@"

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 ?

like image 283
Martin Vegter Avatar asked Jan 31 '26 22:01

Martin Vegter


1 Answers

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 "$@"
like image 168
oguz ismail Avatar answered Feb 02 '26 13:02

oguz ismail