如何使用 getopt(s) 作为在 bash 中传递参数的技术
有人可以向我展示一个如何正确使用 getopts 的示例或我可以在参数中传递的任何其他技术吗?我正在尝试在 unix shell/bash 中写这个。我看到有 getopt 和 getopts ,但不确定哪个更好用。最终,我将构建它以添加更多选项。
在本例中,我想将文件路径作为输入传递给 shell 脚本,并在未正确输入的情况下放置说明。
export TARGET_DIR="$filepath"
例如:(在命令行上调用)
./mytest.sh -d /home/dev/inputfiles
错误消息或提示正确使用,如果这样运行:
./mytest.sh -d /home/dev/inputfiles/
Can someone show me an example how to use getopts properly or any other technique that I would be able to pass in an argument? I am trying to write this in unix shell/bash. I am seeing there is getopt and getopts and not sure which is better to use. Eventually, I will build this out to add for more options.
In this case, I want to pass the filepath as input to the shell script and place a description in the case it wasn't entered correctly.
export TARGET_DIR="$filepath"
For example: (calling on the command line)
./mytest.sh -d /home/dev/inputfiles
Error msg or prompt for correct usage if running it this way:
./mytest.sh -d /home/dev/inputfiles/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
作为用户,我会对一个程序感到非常恼火,该程序在提供带有尾部斜杠的目录名时给我一个错误。如有必要,您可以将其删除。
具有相当完整的错误检查功能的 shell 示例:
有关 getopts 文档,请查看 bash 手册
As a user, I would be very annoyed with a program that gave me an error for providing a directory name with a trailing slash. You can just remove it if necessary.
A shell example with pretty complete error checking:
For getopts documentation, look in the bash manual
对“:)”行的更正:
因为如果在标志后没有提供任何值,则 OPTARG 会获取标志的名称,并将标志设置为“:”,在上面的示例中打印:
这不是有用的信息。
同样适用于:
感谢您提供此示例!
Correction to the ':)' line:
because if no value got provided after the flag, then OPTARG gets the name of the flag and flag gets set to ":" which in the above sample printed:
which wasn't useful info.
Same applies to:
Thanks for this sample!