如何在Shell脚本中以相反的顺序打印参数? [英] How do i print arguments in reverse order in shell script?

查看:198
本文介绍了如何在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.

推荐答案

您需要evalecho,即您需要评估扩展,而不是输出:

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.

这篇关于如何在Shell脚本中以相反的顺序打印参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆