[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] The best way to get the last element of $@
From: |
Dan Douglas |
Subject: |
Re: [Help-bash] The best way to get the last element of $@ |
Date: |
Fri, 20 Mar 2015 18:22:13 -0500 |
On Fri, Mar 20, 2015 at 5:25 PM, Dan Douglas <address@hidden> wrote:
> Greg's way is fine but inefficient and non-portable.
Actually the first way is quite portable (unless you use a bad shell
that lacks local). String subscripting a bit less so, especially for `@'.
Also of course I screwed up my quoting copying from an interactive
shell...
#!/usr/bin/env bash
set foo bar
if ! ${BASH_VERSION+false}; then
# this only works in bash, but is still more portable than printf -v
last=${!#}
elif ! ${KSH_VERSION+false}; then
if [[ ${!KSH_VERSION} == .sh.version ]]; then
# Almighty hack to peek at caller's parameters.
function last.get {
trap 'trap - DEBUG; ((.sh.level--)); eval
".sh.value=\$${#}\${ let .sh.level++; }"' DEBUG
:
}
else
# mksh makes the obvious thing that SHOULD work everywhere actually
# work. Sadly, it can't dereference `#' a second time so
it's still not
# dynamic.
nameref last=$#
fi
else
# For random shells.
eval last=\$$#
fi
# set -ft last.get
echo "$last"
--
Dan Douglas