[英]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 c 风格的循环
Parameter indirect expansion ( ${!i}
towards the bottom of the page) 参数间接扩展(
${!i}
朝页面底部)
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
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!
Just replace echo
by printf "%s\\n"
:只需用
printf "%s\\n"
替换echo
:
#!/bin/sh
o=
for i;do
o="$i $o"
done
printf "%s\n" $o
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.