Print bash arguments in reverse order

前端 未结 5 2161

I have to write a script, which will take all arguments and print them in reverse.

I\'ve made a solution, but find it very bad. Do you have a smarter idea?

相关标签:
5条回答
  • 2021-01-07 05:53

    bash:

    #!/bin/bash
    for i in "$@"; do
        echo "$i"
    done | tac
    

    call this script like:

    ./reverse 1 2 3 4
    

    it will print:

    4
    3
    2
    1
    
    0 讨论(0)
  • 2021-01-07 05:55

    Could do this

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

    This uses the below
    c style for loop
    Parameter indirect expansion (${!i}towards the bottom of the page)

    And $# which is the number of arguments to the script

    0 讨论(0)
  • 2021-01-07 06:08

    Reversing a simple string, by spaces

    Simply:

    #!/bin/sh
    o=
    for i;do
        o="$i $o"
        done
    echo "$o"
    

    will work as

    ./rev.sh 1 2 3 4
    4 3 2 1
    

    Or

    ./rev.sh world! Hello
    Hello world!
    

    If you need to output one line by argument

    Just replace echo by printf "%s\n":

    #!/bin/sh
    o=
    for i;do
        o="$i $o"
        done
    
    printf "%s\n" $o
    

    Reversing an array of strings

    If your argument could contain spaces, you could use bash arrays:

    #!/bin/bash
    
    declare -a o=()
    
    for i;do
        o=("$i" "${o[@]}")
        done
    
    printf "%s\n" "${o[@]}"
    

    Sample:

    ./rev.sh "Hello world" print will this
    this
    will
    print
    Hello world
    
    0 讨论(0)
  • 2021-01-07 06:08

    Portably and POSIXly, without arrays and working with spaces and newlines:

    Reverse the positional parameters:

    flag=''; c=1; for a in "$@"; do set -- "$a" ${flag-"$@"}; unset flag; done
    

    Print them:

    printf '<%s>' "$@"; echo
    
    0 讨论(0)
  • 2021-01-07 06:10

    you can use this one liner:

    echo $@ | tr ' ' '\n' | tac | tr '\n' ' '
    
    0 讨论(0)
提交回复
热议问题