Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

shameless plug If you want to avoid having to write your own args parser everytime or think getopt is a pain, you should check out my little project:

https://github.com/andsens/docopt.sh

No dependencies, the code is directly inlined into your script, and you write the args parser by writing the help-text.



hey='you can define variables' do_this='without commandline parsing' ./thing

#!/bin/sh

hey=${hey:='default one'}

do_this=${do_this:='default two'}

not_that=${not_that:='because getopts is a nightmare'}

echo "${hey} ${do_this} ${not_that}"


If you want to be more DRY (do not repeat yourself) with regard to the variable names you can use the `:` command inside the script (which just expands its arguments) as in

    : ${hey:='default one'}
or even more briefly just use that `:=` {or `=`} assign if empty or unset {or assign if unset} at the first use case.

Also, besides shells most prog.langs have easy ways to receive these { getenv in C, os.environ.get("do_this", "default two") in Python, etc. }.

--

I think what people really miss here is the (rarely used, I guess?) shell calling/invocation syntax @cduzz points out of:

    var1=val1 var2=val2 program
which is notably even more terse than GNU long options:

    program --var1=val1 --var2=val2
Also missing is a documentation standard/convention like:

    help= program
to dump out settings possibilities and their defaults and maybe their types (integer, string, bool, etc.). One virtue of the `:` syntax above is that it is rare enough in "ordinary shell code" that you could probably auto-generate the help from such a table at the top of the script via

    grep '^: ' "$0"
at least if you are willing to assume the invoker sets $0 to a full path.

Soon enough you may outgrow shell programming and, if you become used to such nice conveniences and are willing to learn Nim, I might then recommend something more like https://github.com/c-blake/cligen


I’ve been bashing for decades and never thought of that. Thank you





Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: