以相反的顺序打印 bash 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32647170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:35:14  来源:igfitidea点击:

Print bash arguments in reverse order

bash

提问by Morten Telling

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

回答by 123

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)

这使用以下
c 样式的循环
参数间接扩展${!i}朝向页面底部)

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

$#这是脚本变量的数量

回答by Mohammad Razeghi

you can use this one liner:

你可以使用这个衬垫:

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

回答by Isaac

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

便携和 POSIXly,没有数组并使用空格和换行符:

Reverse the positional parameters:

反转位置参数:

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

Print them:

打印它们:

printf '<%s>' "$@"; echo

回答by Vrata Blazek

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

回答by F. Hauri

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 echoby printf "%s\n":

只需替换echoprintf "%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:

如果您的参数可能包含空格,则可以使用 bash 数组:

#!/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