I have the following condition in a few bash functions to print their help message, but I realized that this is such an annoying repetition and wonder if there's a way around it so that the condition and call happen in a single wrapper function. So instead of this:
fn1() {
arg=$@
[ ! -z $arg ] || [ $arg = "--help" ] && helpit "fn1 help msg." && return
# fn body here
}
fn2() {
arg=$@
[ ! -z $arg ] || [ $arg = "--help" ] && helpit "fn2 help msg." && return
# fn body here
}
We have this:
try_help() {
# FYI $@ is the help msg and not the params of its caller
arg=$@
[ ! -z $arg ] || [ $arg = "--help" ] && helpit "Delete a remote branch by name." && return 1
return 0
}
fn1() {
try_help "fn1 help msg." || return
# fn body here
}
fn2() {
try_help "fn2 help msg." || return
# fn body here
}
Is this possible to do?
arg=$@doesn't work the way you want, btw. It's exactly identical toarg=$*, because$@can't be stored in a string variable at all (it can only be stored in arrays).try_helpfor checking?try_help's argument list.... && helpit "something" && return 1is a bad idea, because it executesreturn 1only ifhelpithas a successful exit status. Better to run... && { helpit "something"; return 1; }so thereturn 1runs even ifhelpitreports a failure.[ -z $arg ]is buggy: When you have an unquoted empty argument list, it turns into no arguments at all, so you get[ -z ], which is treated like[ -n "-z" ], which is why it appears to work. But it only "works" when$argis a simple enough value; considerarg='foo bar'; you get[ -z "foo" "bar" ], which is an invalidtestcommand so the code throws an error instead of just silently returning false as it should.