[英]Print bash arguments in reverse order
我必須編寫一個腳本,它將接受所有參數並反向打印它們。
我已經做了一個解決方案,但發現它很糟糕。 你有更聰明的想法嗎?
#!/bin/sh
> tekst.txt
for i in $*
do
echo $i | cat - tekst.txt > temp && mv temp tekst.txt
done
cat tekst.txt
你可以使用這個襯墊:
echo $@ | tr ' ' '\n' | tac | tr '\n' ' '
重擊:
#!/bin/bash
for i in "$@"; do
echo "$i"
done | tac
將此腳本稱為:
./reverse 1 2 3 4
它會打印:
4
3
2
1
簡單地:
#!/bin/sh
o=
for i;do
o="$i $o"
done
echo "$o"
將作為
./rev.sh 1 2 3 4
4 3 2 1
或者
./rev.sh world! Hello
Hello world!
只需用printf "%s\\n"
替換echo
:
#!/bin/sh
o=
for i;do
o="$i $o"
done
printf "%s\n" $o
如果您的參數可能包含空格,則可以使用 bash 數組:
#!/bin/bash
declare -a o=()
for i;do
o=("$i" "${o[@]}")
done
printf "%s\n" "${o[@]}"
樣本:
./rev.sh "Hello world" print will this
this
will
print
Hello world
便攜和 POSIXly,沒有數組並使用空格和換行符:
反轉位置參數:
flag=''; c=1; for a in "$@"; do set -- "$a" ${flag-"$@"}; unset flag; done
打印它們:
printf '<%s>' "$@"; echo
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.