I often need to pop the last positional argument of a bash function or script.
By "pop" I mean: "remove it from the list of positional arguments, and (optionally) assign it to a variable."
Given how frequently I need this operation, I am a bit surprised that best I have found is what is illustrated by the example below:
foo () {
local argv=( "$@" )
local last=${argv[$(( ${#argv[@]} - 1 ))]}
argv=( ${argv[@]:0:$(( ${#argv[@]} - 1 ))} )
echo "last: $last"
echo "rest: ${argv[@]}"
}
In other words, an epic production featuring a cast of thousands...
Is there anything simpler, easier to read?
shift
keyword is that removing the first element from the list of positional parameters is a common thing to want to do. Care to say something about your use cases? – Kusalananda Sep 27 '20 at 20:38$(( ))
could be removed without impact, but Quasímodo has the actual answer. – bxm Sep 27 '20 at 20:45mv
andcp
have a "special" last parameter, so it's conceivable that kjo's use-case conforms to Unix conventions as well. – ruakh Sep 29 '20 at 16:19