我正在制作一个智能别名gc
,可以区分git commit / checkout。
如果gc
被称为不带任何参数或使用-a
,-m
参数,然后git的承诺运行。否则,将运行git checkout(如果存在b
带有附加参数的标志)。如果调用了gc的任何其他变体,我宁愿它引发错误而不是做意外的事情。
到目前为止,这是我的shell函数。
gc() {
args=$@
commit=false
checkout=false
# Check flags
while getopts ":am:b" opt; do
case $opt in
a|m)
commit=true
;;
b)
checkout=true
;;
\?)
echo "Unknown flags passed."
return 1
;;
esac
done
shift "$((OPTIND-1))"
# Check number of arguments
if [[ "$#" == 0 ]]; then
commit=true
elif [[ "$#" == 1 ]]; then
checkout=true
else
echo "Too many arguments"
return 1
fi
# Finally run respective command
if [[ $commit == true && $checkout == true ]]; then
echo "Unable to ascertain which operation you would like to perform."
return 1
elif [[ $commit == true ]]; then
git commit "$args"
elif [[ $checkout == true ]]; then
git checkout "$args"
else
echo "Undefined behavior"
return 1
fi
}
但是,这不能正常工作。经过一些试验,我发现分配$@
给另一个变量是根本原因,但我无法理解为什么以及到底出了什么问题。
另外,在我第一次编写shell函数时,请突出显示我犯的任何错误。
$@
是一个数组,将其分配给一个数组:
args=("$@")
然后将其用作数组:
elif [[ $commit == true ]]; then
git commit "${args[@]}"
elif [[ $checkout == true ]]; then
git checkout "${args[@]}"
else
当前代码中发生的事情是所有单独的参数都存储为单个字符串。因此,如果您致电:
bc -a "foo bar"
这被分配args
为:
args='-a foo bar'
然后,而不是执行:
git commit -a "foo bar"
你得到:
git commit '-a foo bar'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句