如何编写脚本执行git pull操作?

4

dev/staging/production服务器上执行git pull是一个常见的做法。我经常这样做,我在运行Linux的生产服务器上几乎每天都要执行100次git pull。

我想,现在是时候编写一个脚本来改进这个过程了。


pull.sh将执行以下三个命令:

  • git pull
  • 在提示时输入我的密码
  • service nginx reload

我已经尝试在这里创建我的pull.sh

#!/bin/bash

function pull {
  git pull
  password
  service nginx reload
}


pull ;

结果

运行我给出的脚本后,仍然会提示输入密码。

enter image description here


任何线索/帮助/建议将不胜感激!


哪个应用程序要求您输入密码? - Orest Hera
你尝试了什么?在这个过程中,你访问了哪些网站?从你所寻找的意义上来说,这并不是一个研究性的网站。 - Mad Physicist
每一次我执行 git pull 命令时,通常都会提示我输入密码。 - code-8
那很可能是通过ssh远程连接。 - Mad Physicist
@MadPhysicist:我更新了我的帖子,展示了我目前得到的东西。 - code-8
1
为什么要在各处使用 eval - Mad Physicist
2个回答

9
您可以使用expect脚本与git身份验证进行交互:
#!/usr/bin/expect -f
spawn git pull
expect "ass"
send "your_password\r"
interact

它等待匹配"Password"、"password"或"passphrase"的"ass"文本,然后发送您的密码。 该脚本可从另一个bash脚本调用,以重新启动您的服务器。
# Call script directly since the shell knows that it should run it with
# expect tool because of the first script line "#!/usr/bin/expect -f"
./git-pull-helper-script.sh
# Without the first line "#!/usr/bin/expect -f" the file with commands
# may be sent explicitly to 'expect':
expect file-with-commands

# Restart server
service nginx reload

@ihue,你需要将提示字符串调整为你的“输入...”。 - Orest Hera
可以的。您介意解释一下 bin/expect -f 是什么吗? - code-8
\rinteract - code-8
1
#!/usr/local/bin/expect -f 这行代码告诉您的系统使用 expect 应用程序处理脚本:http://linux.die.net/man/1/expect Expect 从 cmdfile 中读取要执行的命令列表。在支持 #! 符号的系统上,还可以通过将脚本标记为可执行文件并使脚本的第一行成为 #!/usr/local/bin/expect -f 来隐式调用 Expect。 - Orest Hera
1
这个脚本不是由bash处理的,而是由另一个应用程序expect解释的。一旦expect脚本完成,您可以运行其他shell命令,如service nginx reload - Orest Hera
显示剩余3条评论

3
处理密码短语的方法是使用ssh代理:这样,您只需输入一次密码短语即可。 我在我的开发用户的~/.bash_profile中有这个。
# launch an ssh agent at login, so git commands don't need to prompt for password
# ref: https://dev59.com/iGMk5IYBdhLWcg3w5Bzy#18915067

SSH_ENV=$HOME/.ssh/env

if [[ -f ~/.ssh/id_rsa ]]; then
    function start_agent {
        # Initialising new SSH agent...
        ssh-agent | sed 's/^echo/#&/' > "${SSH_ENV}"
        chmod 600 "${SSH_ENV}"
        source "${SSH_ENV}" > /dev/null
        ssh-add
    }

    # Source SSH settings, if applicable

    if [ -f "${SSH_ENV}" ]; then
        source "${SSH_ENV}" > /dev/null
        agent_pid=$(pgrep ssh-agent)
        (( ${agent_pid:-0} == $SSH_AGENT_PID )) || start_agent
        unset agent_pid
    else
        start_agent
    fi
fi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接