我在一些 bash 函式中有以下條件來列印他們的幫助訊息,但我意識到這是一個令人討厭的重復,并且想知道是否有辦法解決它,以便條件和呼叫發生在單個包裝函式中。所以代替這個:
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
}
我們有這個:
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
}
這可能嗎?
uj5u.com熱心網友回復:
輕而易舉地完成了。
helpit() { echo "$*" >&2; }
try_help() {
local help_msg arg
help_msg=$1; shift
if (( $# == 0 )); then
echo "No arguments found. Printing help:" >&2
helpit "$help_msg"
return 1
fi
for arg in "$@"; do
case $arg in
--) return 0;;
--help) helpit "$help_msg"; return 1;;
esac
done
return 0
}
fn1() {
try_help "fn1 help msg" "$@" || return
# fn body here
}
fn2() {
try_help "fn2 help msg" "$@" || return
# fn body here
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455990.html
標籤:重击
