首页 文章

使用cronjob进行Git自动拉取

提问于
浏览
49

我正在尝试创建一个cronjob,其任务是每分钟做一次 git pull ,以使我的 生产环境 站点与我的主分支保持同步 .

由于权限问题,git pull需要由系统用户 nobody 完成 . 但是,似乎不允许运行命令 nobody 帐户 . 所以我必须创建作为 root 用户的任务 .

我试过的crontab条目:

*/1 * * * * su -s /bin/sh nobody -c 'cd ~heilee/www && git pull -q origin master' >> ~/git.log

它不起作用,我不知道如何调试它 .

有人可以帮忙吗?

UPDATE1: git pull 命令本身是正确的 . 我可以毫无错误地运行它 .

5 回答

  • 27

    解:

    */1 * * * * su -s /bin/sh nobody -c 'cd ~dstrt/www && /usr/local/bin/git -q pull origin master'
    
  • 10

    虽然你确实需要弄清楚如何让更新在第一时间工作,但你最好还是使用上游的钩子来实现它 . 你可以简单地使用来自 post-commit 钩子的curl来做这件事,或者如果你正在使用github,只需在他们一边使用post-receive钩子 .

  • 3
    */1 * * * * su -s /bin/sh nobody -c 'cd /home/heilee/src/project && /usr/bin/git pull origin master'
    

    这纠正了一些错误,这些错误阻止了我的系统(Ubuntu> 10.04服务器)上接受的答案 . 关键变化似乎是在 pull 之后的 -q 而不是之前 . 你赢了't notice that your pull isn' t工作,直到你拖尾 /var/log/syslog 文件或尝试运行你未更新的 生产环境 代码 .

  • 5
    #!/bin/bash
    cd /home/your_folder/your_folder && /usr/bin/git pull git@bitbucket.org:your_user/your_file.git
    

    这是我一直在使用和工作

  • 1

    我创建了一个小脚本来处理它 . 然后可以使用by命令crontab

    crontab -e
    0 2 * * * cd /root && ./gitpull.sh > /root/log/cron.log  2>&1 &
    

    这是 gitpull.sh

    #!/bin/bash
    
    source /etc/profile
    PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
    export PATH
    export TERM=${TERM:-dumb}
    
    #----------------------------------------
    # Please set the following variable section
    # Please set up working directories, use','split
    # eg:path="/root/test/path1,/root/test/path2"
    path=""
    #----------------------------------------
    
    # Do not edit the following section
    
    # Check if user is root
    [ $(id -u) != "0" ] && { echo "${CFAILURE}Error: You must run this script as root.${CEND}"; exit 1; } 2>&1
    
    # Check if directory path exists
    if [[ "${path}" = "" ]]; then 
        echo "${CFAILURE}Error: You must set the correct directory path.Exit.${CEND}" 2>&1
        exit 1
    fi
    
    # Check if command git exists
    if ! [ -x "$(command -v git)" ]; then
        echo "${CFAILURE}Error: You may not install the git.Exit.${CEND}" 2>&1
        exit 1
    fi
    
    # Check where is command git
    git_path=`which git`
    
    # Start to deal the set dir
    OLD_IFS="$IFS" 
    IFS="," 
    dir=($path) 
    IFS="$OLD_IFS" 
    
    echo "Start to execute this script." 2>&1
    
    for every_dir in ${dir[@]} 
    do 
        cd ${every_dir}
        work_dir=`pwd`
        echo "---------------------------------" 2>&1
        echo "Start to deal" ${work_dir} 2>&1
        ${git_path} pull
        echo "---------------------------------" 2>&1
    done
    
    echo "All done,thanks for your use." 2>&1
    

    我们必须设置工作目录

相关问题