如何在Shell脚本中以相反的顺序打印参数?
我试图编写一个脚本,以相反的顺序打印参数. 所以如果我输入bash reverse.sh一二三 我希望我的输出是三二一 我怎样才能做到这一点? 这是我尝试过的方法,显然不起作用...
I was trying to write a script that print the arguments in reverse order. So if I type bash reverse.sh one two three I expect my output to be three two one How can i do this? This is what I tried and it obviously didn't work...
#!/bin/bash
i=0
a="$"
for word in $*; do
echo $a$(($#-i))
i=$((i+1))
done
这是我得到的输出
$3
$2
$1
我认为这会按3、2、1的顺序打印参数,但没有.我该怎么办?任何帮助都感激不尽.谢谢.
I thought this would print the parameters in order 3, 2, 1 but it didn't. How should I do it? Any help will be much appreciated. Thank you.
您需要eval
和echo
,即您需要评估扩展,而不是输出:
You need eval
with echo
i.e. you need to evaluate the expansion, not output it:
eval echo $a$(($#-i))
请注意,一般不建议使用eval
,因为如果未清理输入字符串,这可能会导致安全隐患.检查 John1024的答案,以了解如何在没有eval
的情况下完成此操作.
Note that, using eval
in general is discouraged as this could result in security implications if the input string is not sanitized. Check John1024's answer to see how this can be done without eval
.