help-bash
[Top][All Lists]
Advanced

[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 17:25:49 -0500

Eric's way is fine but non-portable. Greg's way is fine but
inefficient and non-portable. It's equally safe and POSIX-compatible
to use a simple assignment:

    eval last=\$$#

Another way is to do some version detection. This code creates a
dynamic reference to the last parameter in ksh93 and mksh, but needs
to be re-evaluated when the parameters are modified in Bash and other
shells that can't do this.

    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.
            nameref last=\#
        fi
    else
        # For random shells.
        eval last=\$$#
    fi

-- 
Dan Douglas



reply via email to

[Prev in Thread] Current Thread [Next in Thread]