I've just found out that getopt
is not cross-platform (in particular for FreeBSD and Linux). What is the best workaround for this issue?
相关问题
- How to get the return code of a shell script in lu
- JQ: Select when attribute value exists in a bash a
- Invoking Mirth Connect CLI with Powershell script
- Advice for supporting both Mac and Windows Desktop
- Emacs shell: save commit message
相关文章
- 使用2台跳板机的情况下如何使用scp传文件
- In IntelliJ IDEA, how can I create a key binding t
- Check if directory exists on remote machine with s
- shell中反引号 `` 赋值变量问题
- How get the time in milliseconds in FreeBSD?
- How do you make an installer for your python progr
- Libgdx - Check if a key is being held down?
- Is there a non-java, cross platform way to launch
Use
getopts
(with an "s").According to Bash FAQ 35:
Basic syntax for
getopt
is cross-platform.There are essentially two versions of the
getopt
command: the original version and the GNU enhanced version. The GNU enhanced version is backward compatible with the original version, so if you only use the features of the original version it will work with both.Detect which version of getopt is available
You can detect which version is available and use the enhanced features if the GNU enhanced version is available, and limit yourself to the original features if the GNU enhanced version is not available. The enhanced version has a
-T
option for testing which version is available.Consider using built-in shell command
getopts
(with an "s") instead, because it is more portable. However,getopts
does not support long options (e.g.--help
).If you like long options, use
getopt
and use the above test to see if the GNU enhanced version ofgetopt
is available or not. If the enhanced version is not available, the script can gracefully degrade to either using the original version ofgetopt
(with no support for long option names and no whitespace support) or usinggetopts
(with no support for long option names).Using GNU enhanced getopt properly
Getting the GNU enhanced version to process arguments with whitespace properly is tricky. Here's how it is done:
The secret is to use
"$@"
where the double quotes are very important (in line 1), and toeval
the set command (in line 6).So errors raised by
getopt
can be detected and handled, the call togetopt
is done separately from theeval
with the two linked by the ARGS variable.Complete working example
This example can be downloaded from https://gist.github.com/hoylen/6607180
The comparison table on Wikipedia's entry on getopts compares the different features.
The Bash builtin getopts function can be used to parse short and long options portably, see:
Using getopts in bash shell script to get long and short command line options