Print bash arguments in reverse order

前端 未结 5 2160

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 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
    

提交回复
热议问题