I am writing scripts with the following boilerplate CLI pattern:
usage(){
echo "$0 yada yada"
...
echo
}
for arg in "$@"; do
case "$arg" in
'--help|-help') set -- "$@" '-h';;
...
esac
done
OPTIND=1
while getopts 'h...' opt; do
case "$opt" in
'h') usage; exit 0;;
...
esac
done
shift $((OPTIND-1))
Is there any way to compress or encapsulate this in BASH on linux with other tools, perhaps an additional dependency?
grepfor instance,grep -e --help -- --helpis meant to look for--helpin the file called--help, but you would end up transforming that togrep -e -h -- -h. Also with the standard CLI interfacecmd -helpis meant to be the same ascmd -h -e -l -p(orcmd -h -e lpif the-eoption takes an argument, etc). See getopt, getopts or manual parsing - what to use when I want to support both short and long options? and many other Q&As here for approaches at parsing long options – Stéphane Chazelas Jul 25 '23 at 16:45grep '\-\-help', even after adding quotes, so this is beside the point, imo. Yes, there are other ways, this is a simple one and I am looking for an even simpler way. – Chris Jul 25 '23 at 16:55-h, -e, -l, -pthen a user could eventually stumble on a surprise. I am probably not going to change things for now, since the goal is for the user to stumble onhelp. If the edge case becomes an issue, I'll change it. – Chris Jul 25 '23 at 16:57-is not a regex operator so putting backslash in front of it yields unspecified behaviour. Togrepfor--help, you use eithergrep -- --help filewhere--marks the end of options orgrep -e --help fileorgrep -e--help filewhere--helpis the argument to the-eoption. – Stéphane Chazelas Jul 25 '23 at 16:57grepin cross platform scripts. Surely in some contexts you are right, but it's got nothing to do with my question. In fact, I don't need to use-- --helpto work with bash if I escape the dashes, and I don't need to use--regexp(-e) either. – Chris Jul 25 '23 at 16:58grep '\.' fileto look for a literal.or to introduce some other operators, like ingrep '\([[:upper:]]\{4\}\)\1'to look for a repeated sequence of 4 uppercase letters.grep '\-\-help'is just plain wrong even if in mostgrepimplementations it will do the same asgrep -e --help. – Stéphane Chazelas Jul 25 '23 at 17:01getoptor other option parsing tools/library, then you don't need to worry about all that. It will also properly handle unambiguous long option abbreviation (like--h/--he) here assuming it's the only long option that starts withh/he) and--input=fooin addition to--input fooand-ifoo+-i foo, etc. – Stéphane Chazelas Jul 25 '23 at 17:04getoptsbuilt-in – Chris Jul 25 '23 at 17:22