Bourne Shell 脚本打印最后一个参数
我正在尝试创建一个 bourne shell 脚本,它将接受 0 个或多个参数并打印出最后一个参数,我习惯于编写 Java,对此感到很困惑,慢慢开始学习 C。
Im trying to create a bourne shell script that will take 0 or more arugments and print out the last arugment, I am use to writing Java and im so confused by this, slowly starting to learn C.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
@Michael 解决方案的替代方案:
$@
是包含所有参数的数组。:
用于正常分割字符串(您可以尝试使用echo "${USER: -1}"
来验证它是否打印您用户名的最后一个字符) ,但也可以用于数组来获取最后一个元素。if [ "${@: -1}" = "--help" ]
)An alternative to @Michael's solution:
$@
is the array with all the parameters.:
is used to split strings normally (you can try this withecho "${USER: -1}"
to verify that it prints the last character of your user name), but can also be used for arrays to get the last element.if [ "${@: -1}" = "--help" ]
)这是一个简短的 Bash 脚本,可以完成此操作:
不过,这不是 Bourne shell 脚本。参数不是使用
read
命令从键盘读取的。相反,它们是在运行脚本时在命令行上提供的。例如,如果您将此文本放入script.sh
并运行./script.sh abcd e
它将打印:Here is a short Bash script that will do it:
This is not a Bourne shell script, though. Args are not read from the keyboard with the
read
command. Instead they are supplied on the command line when running your script. For example, if you put this text inscript.sh
and run./script.sh a b c d e
it will print:在 bash 中:
你的问题提到了 C。在 C 中更容易:
In bash:
Your question mentions C. In C its easier:
这应该有效:
这适用于
/bin/sh
是bash
或dash
。我无法用“真正的”
/bin/sh
来测试它,无论它是什么。This should work:
This works with
/bin/sh
beingbash
ordash
.I am unable to test it with a "real"
/bin/sh
, whatever that would be.