一直想知道这一点,但从未充分调查过 - 有没有办法在 bash 中获取命名参数?
例如,我有这个:
function ql_maybe_fail {
if [[ "$1" == "true" ]]; then
echo "quicklock: exiting with 1 since fail flag was set for your 'ql_release_lock' command. "
exit 1;
fi
}
是否有可能将其转换为这样的东西:
function ql_maybe_fail (isFail) {
if [[ "$isFail" == "true" ]]; then
echo "quicklock: exiting with 1 since fail flag was set for your 'ql_release_lock' command. "
exit 1;
fi
}
答案1
Bash 中的函数当前不支持用户命名参数。
答案2
这个解决方法可能会有所帮助,但它不是很好的测试:
fun () {
v1=$1
v2=$2
for v in "$v1" "$v2"
do
case "$v" in
name=*) name=${v/*=/};;
age=*) age=${v/*=/};;
*) echo "unexpected $v, please use name and age" ;;
esac
done
echo "name=$name age=$age"
}
输出:
fun "name=John" "age=22"
name=John age=22
fun "age=22" "name=John"
name=John age=22