[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: |
John Kearney |
Subject: |
Re: [Help-bash] The best way to get the last element of $@ |
Date: |
Sat, 21 Mar 2015 00:33:17 +0100 |
another option might be
ks_GetElement(){
local cnt=$1
unset ReturnValue
[ $cnt -ge 0 ] || cnt=$(($#+$cnt))
while shift && [ $# -gt 0 ] ; do
[ $((cnt-=1)) -eq 0 ] || continue
break;
done
ReturnValue=${1:-<unset>}
echo "ReturnValue=${ReturnValue}"
}
set -- arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
ks_GetElement 1 "$@"
ks_GetElement -1 "$@"
ks_GetElement 5 "$@"
ks_GetElement -5 "$@"
ks_GetElement 11 "$@"
gives you this
ReturnValue=arg1
ReturnValue=arg10
ReturnValue=arg5
ReturnValue=arg6
ReturnValue=<unset>
On Sat, Mar 21, 2015 at 12:22 AM, Dan Douglas <address@hidden> wrote:
> 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
>
>