3 ms·
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=
by cduzz 4y ago
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}"
- tambourine_man 4y agoI’ve been bashing for decades and never thought of that. Thank you
- cb321 4y agoYou might also see ideas in https://news.ycombinator.com/item?id=34147636 https://news.ycombinator.com/item?id=34147636
- cb321 4y agoIf 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 https://github.com/c-blake/cligen