Access the last argument passed in the bash function and then transfer it

I have a simple function in bash that I want to accept for any number of arguments. What I would like to do is repeat the last argument passed to the function, and then shift and repeat until I'm out of the arguments.

Here is my code:

test(){
    while [ $# -ne 0 ]
    do
        echo "${@: -1}"
        shift  
    done
}

However, the shift does not seem to be taking place.

If I run:

test a b c d

he will return

d
d
d
d

While I obviously would like to return

d
c
b
a

What am I doing wrong? Thank you :)

+4
source share
2 answers

shiftdoes not delete the last argument, it removes the first. $2becomes $1, $3becomes $2, etc. dwill always be the last argument, because objects fly out in front.

, :

for ((i = $#; i > 0; --i)); do
    echo "${!i}"
done

:

while (($# > 0)); do
    echo "${@: -1}"
    set -- "${@:1:$#-1}"
done

, ${@: -1} ${!#}. . - , Perl script.

+4

:

revargs() {
    local sgra=()
    for arg; do sgra=("$arg" "${sgra[@]}"); done
    printf "%s\n" "${sgra[@]}"
}
revargs foo bar baz qux
qux
baz
bar
foo

: , .

revargs() {
    printf "%s\n" "$@" | tac
}
+1

Source: https://habr.com/ru/post/1546209/


All Articles