hub
我有一个用于轻松创建的bash 脚本pull-requests
。在 bash 中它运行良好,我只需键入gpr <base_branch>
代码并执行逻辑即可。
# git pr
function gpr() {
# exit if no base branch supplied
if [[ ! $1 ]]; then
echo "No base branch supplied. Exiting"
return
fi
if [[ ! $2 ]]; then
echo "Creating pull-request"
echo "No pull-request message set."
read -p "Do you want to use the last commit message as pull-request message. Y or N? " choice
if [[ $choice =~ ^[Yy]$ ]]; then
# Use last commit message
COMMIT=$(git log -1 HEAD --pretty=format:%s)
echo "Using last commit message: $COMMIT"
MESSAGE="-m '$COMMIT'"
else
# Use own message
read -p "Enter message: " message
MESSAGE=-"m '$message'"
fi
fi
COMMAND="hub pull-request -b $1 $MESSAGE"
echo "Creating pull-request against $1 branch with message: $MESSAGE"
eval $COMMAND
echo "Pull-request created successfully"
}
最终将导致hub pull-request -b <base_branch> -m <pull-request message or last commit message>
但是我如何将其转换为zsh
?
我尝试粘贴代码,.zshrc
但似乎不起作用。运行时我得到以下信息gpr <base_branch>
gpr develop
Creating pull-request
No pull-request message set.
gpr:read:10: -p: no coprocess
gpr:read:18: -p: no coprocess
Creating pull-request against develop branch with message: -m ''
And vim appears
在 bash 中,过程如下
gpr develop
Creating pull-request
No pull-request message set.
Do you want to use the last commit message as pull-request message. Y or N? y
Using last commit message: [UIUX-x] Commit message
Creating pull-request against develop branch with message: -m '[UIUX-x] Commit message'
https://github.com/<author>/<repo>/pull/<num>
Pull-request created successfully
答案1
问题在于 zsh 的read
函数采用的选项与 bash 不同。在 bash 中,read -p
指定提示符;在 zsh 中,它表示从协进程(不存在)读取。您需要切换到 zsh 语法,该语法将提示符放在要读取的变量之后(以问号分隔):
read "choice?Do you want to use the last commit message as pull-request message. Y or N? "
...
read -p "message?Enter message: "
此外,我还要提出另外两个建议(针对 bash 和 zsh):首先,使用小写或混合大小写的变量名;有大量全大写的变量名对 shell、系统等具有特殊含义(并且 bash 和 zsh 之间的含义并不相同),并且很容易意外重复使用其中一个并导致奇怪的后果。
其次,在变量中构建命令,然后eval
将其不是安全(在 bash 或 zsh 中)。使用数组或直接输入信息(和只是将消息)放在变量中并直接执行命令:
if ...
message=$commit
else ...
read message
fi
echo "Creating pull-request against $1 branch with message: $message"
hub pull-request -b "$1" -m "$message"