简体   繁体   English

/bin/sh 替代 /bin/bash 中的 ${!#}

[英]/bin/sh alternative to ${!#} in /bin/bash

I'm trying to understand what is the alternative of ${!#} of /bin/bash on /bin/sh ?我试图了解/bin/sh /bin/bash${!#}的替代方案是什么?

I know that ${!#} , which evaluated to ${0} on /bin/bash but how can I get it using /bin/sh ?我知道${!#} ,它在/bin/bash上评估为${0}但我怎样才能使用/bin/sh得到它?

The closest approximation you can get in sh is an eval -based solution.您可以在 sh 中获得的最接近的近似值是基于eval的解决方案。

eval echo "\$${#}"

But keep in mind that eval is very dangerous if not used carefully.但请记住,如果不小心使用 eval 是非常危险的。 I'd recommend considering if you need indirection or not before implementing.我建议在实施之前考虑是否需要间接。

For example, the above code basically reduces to "print the last argument."例如,上面的代码基本上简化为“打印最后一个参数”。 You could write this without using indirection or eval:您可以在不使用间接或 eval 的情况下编写此代码:

for arg in "${0}" "${@}" ; do
:
done
echo "${arg}"

There is nothing wrong with using eval in this case.在这种情况下使用eval没有任何问题。

You should wrap $# in curly braces though;不过,您应该将$#包裹在花括号中; otherwise it won't work when the number of positional parameters exceeds nine.否则当位置参数的个数超过九个时它将不起作用。 See:看:

$ set -- a b c d e f g h i j
$ eval "arg=\$$#"
$ echo "$arg"
a0
$
$ eval "arg=\${$#}"
$ echo "$arg"
j

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM