如何使用 Git 将本地目录同步到服务器?

lag*_*lex 1 ftp ssh sync git

如何使用 Git 来简单地使本地目录与服务器目录保持同步?

我习惯使用 FTP,但它速度慢且容易出错。

我可以通过 SSH 访问服务器。我可以在服务器上运行 Git。

我还想避免使用第三方 Git 托管服务,例如 Github 或 Bitbucket。我希望能够直接上传到我的服务器。

lag*_*lex 6

在本地机器上:

  1. 初始化要同步的目录为 Git 存储库

    git init
    
    Run Code Online (Sandbox Code Playgroud)

    提交任何现有代码

    git add -A
    git commit -am "initial commit"
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将其远程设置为服务器

    git remote set-url origin user@server:/path/to/dir/on/server
    
    Run Code Online (Sandbox Code Playgroud)

    在哪里

    • user是您用于 SSH 到您的server. 例如。根@10.10.10.10

    • /path/to/dir/on/server是服务器上您希望将更改同步到的目录

    旁注:建议SSH 登录不要使用密码

在远程机器上:

  1. 在服务器上初始化一个空目录

    mkdir /path/to/dir/on/server
    cd /path/to/dir/on/server
    git init
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将其配置设置为忽略已签出分支的更新

    git config receive.denyCurrentBranch ignore
    
    Run Code Online (Sandbox Code Playgroud)

    这是必需的,因为(引用如果不这样做您将得到的确切错误)“更新非裸存储库中的当前分支被拒绝,因为这将使索引和工作树与您推送的内容不一致,并且需要‘git reset --hard’来将工作树与 HEAD 匹配。 ”(我们实际上会在下一步中这样做)。

  3. 设置post-receive git hook

    post-receive在目录中创建一个文件.git/hooks,然后在编辑器中打开它:

    vim .git/hooks/post-receive
    
    Run Code Online (Sandbox Code Playgroud)

    将以下内容放入其中:

    #!/bin/sh
    git --git-dir=. --work-tree=.. checkout -f
    
    Run Code Online (Sandbox Code Playgroud)

    将其模式设置为可执行:

    chmod +x .git/hooks/post-receive
    
    Run Code Online (Sandbox Code Playgroud)

    每当您推送任何内容时,这都会检查服务器目录上的最新更改。

  • 以上所有内容的一行:

    dir=<dir>; mkdir $dir && cd $dir && git init && git config receive.denyCurrentBranch ignore && printf '#!/bin/sh\ngit --git-dir=. --work-tree=.. checkout -f' > .git/hooks/post-receive && chmod +x .git/hooks/post-receive
    
    Run Code Online (Sandbox Code Playgroud)

现在在本地计算机上您可以执行以下操作:

git commit -am "Some changes"
git push
Run Code Online (Sandbox Code Playgroud)

您的本地目录将同步到服务器目录。


我经常使用的另一个方法是:在本地计算机上,我保留originGithub/Bitbucket 的远程名称(该项目的“主页”),以及一个特殊的server远程名称(该名称是其部署位置)。我还创建了一个 git 分支(也已命名)server并将其配置为始终推送到server远程:

git config branch.server.remote server
git config remote.server.push server:master
Run Code Online (Sandbox Code Playgroud)

这样,每当我在主分支上时,它都会推送到origin(Github/Bitbucket 等),而当我在server分支上时,它会推送到服务器。