git clone的Shell脚本不适用于变量作为密码

时间:2019-10-24 21:59:25

标签: git shell

我在使用git的shell脚本时遇到了麻烦,该脚本会询问机器人用户帐户的密码,以进行如下克隆/推送:

echo 'write the pass'
read pass
git clone https:\\user:$pass@bitbucket... destination

问题在于它向我显示: fatal: Authentication failed for 'https:\\user:$pass@bitbucket...'

我尝试了https:\\user:${pass}@bitbucket...,但结果相同

如果我不带任何变量直接尝试 git clone https:\\user:password@bitbucket... destination 效果很好。

你们知道这是什么问题吗?

1 个答案:

答案 0 :(得分:0)

您在这里遇到了几个问题。一种是您使用反斜杠而不是正斜杠。外壳可能无法很好地解释这一点。

另一个问题是引号问题:您的密码中可能有空格,如果这样,shell会将其解释为两个参数。

最后,如果您使用的密码包含某些字符,则需要转义它们才能使密码正常工作。例如,某些密码包含等号,必须将其编码为%3D。在shell中没有一种很好的方法,但是如果您安装了Perl(您可能使用Git进行了安装),则可以将其更改为以下内容:

echo 'write the pass'
read pass
pass="$(echo "$pass" | perl -pe 's/([^A-Za-z0-9._~-])/sprintf "%%%02X", ord($1)/ge')"
git clone https://user:$pass@bitbucket.org/...

由于百分比编码的密码永远不会包含空格,因此不再需要用引号引起来。