简体   繁体   中英

Print bash arguments in reverse order

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?

#!/bin/sh
> tekst.txt

for i in $* 
do
    echo $i | cat - tekst.txt > temp && mv temp tekst.txt
done

cat tekst.txt

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

你可以使用这个衬垫:

echo $@ | tr ' ' '\n' | tac | tr '\n' ' '

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM