Difference between revisions of "Git (简体中文)"

From ArchWiki
Jump to: navigation, search
(update templates, see Help:Style)
(12 intermediate revisions by 6 users not shown)
Line 1: Line 1:
[[Category: Development (简体中文)]]
+
[[Category: Version Control System (简体中文)]]
 
[[Category: 简体中文]]
 
[[Category: 简体中文]]
{{i18n|Git}}
+
[[en:Git]]
{{Translateme}}
+
{{translateme (简体中文)}}
 
{{Article summary start|摘要}}
 
{{Article summary start|摘要}}
 
{{Article summary text|安装和使用 Git 版本管理系统}}
 
{{Article summary text|安装和使用 Git 版本管理系统}}
Line 22: Line 22:
  
 
Bash 自动完成 (例如,按 tab 来完成你正在键入的命令),只需要:
 
Bash 自动完成 (例如,按 tab 来完成你正在键入的命令),只需要:
source /usr/share/git/completion/git-completion.bash
+
{{bc|source /usr/share/git/completion/git-completion.bash}}
 
另外,你可以安装 {{Pkg|bash-completion}} 软件包来自动为新的外壳加载自动完成。
 
另外,你可以安装 {{Pkg|bash-completion}} 软件包来自动为新的外壳加载自动完成。
  
 
如果你想使用 Git 内建的图形界面 (例如 {{Ic|gitk}} 或者 {{Ic|git gui}}) 你需要安装 {{Pkg|tk}} 软件包,否则你会遇到一个隐晦的错误信息:
 
如果你想使用 Git 内建的图形界面 (例如 {{Ic|gitk}} 或者 {{Ic|git gui}}) 你需要安装 {{Pkg|tk}} 软件包,否则你会遇到一个隐晦的错误信息:
/usr/bin/gitk: line 3: exec: wish: not found.
+
{{bc|/usr/bin/gitk: line 3: exec: wish: not found.}}
  
 
== 配置 ==
 
== 配置 ==
Git reads its configuration from a few INI type configuration files.  In each git repository {{ic|.git/config}} is used for configuration options specific to that repository.  Per-user ("global") configuration in {{ic|$HOME/.gitconfig}} is used as a fall-back from the repository configuration.  You can edit the files directly but the preferred method is to use the git-config utility. For example,
+
Git 从几个 INI 格式的配置文件中读取配置信息。在每一个 git 仓库中 {{ic|.git/config}} 被用来指定与本仓库有关的配置选项。每一个用户 ("global") 的配置文件在 {{ic|$HOME/.gitconfig}} 被用来作为仓库配置的备用配置。你也可以直接编辑文件,但是更推荐的方法是使用 git-config 工具。例如,
 
  $ git config --global core.editor "nano -w"
 
  $ git config --global core.editor "nano -w"
adds {{Ic|<nowiki>editor = nano -w</nowiki>}} to the {{Ic|<nowiki>[core]</nowiki>}} section of your {{ic|~/.gitconfig}} file.
+
会添加 {{Ic|<nowiki>editor = nano -w</nowiki>}} 到 {{ic|~/.gitconfig}} 文件的 {{Ic|<nowiki>[core]</nowiki>}} 部分中。
  
The [http://www.kernel.org/pub/software/scm/git/docs/git-config.html man page for the git-config] utility has a fairly long list of variables which can be set.
+
[http://www.kernel.org/pub/software/scm/git/docs/git-config.html git-config 工具的 man page] 有一个很长的参数列表,列出所以可以设置的变量。
  
Here are some more basic configurations you will probably want:
+
这是一些你可能用到的常见的配置:
 
  $ git config --global user.name "Firstname Lastname"
 
  $ git config --global user.name "Firstname Lastname"
 
  $ git config --global user.email "your_email@youremail.com"
 
  $ git config --global user.email "your_email@youremail.com"
Line 41: Line 41:
 
  $ git config --global --list
 
  $ git config --global --list
  
==Cheatsheet==
+
==基本用法==
Parts from everywhere, much from the wonderful tutorial here: http://schacon.github.com/git/gittutorial.html
+
  
Additionally see [[Super Quick Git Guide]].
+
===克隆一个版本库===
  
Pull the network scripts with
+
  git clone <repo location> <dir>
  git clone <nowiki>http://archlinux.org/~james/projects/network.git</nowiki>
+
Update an existing clone
+
git pull origin
+
Commit changes
+
git commit -a -m "changelog message"
+
To create a new branch
+
git branch somebranch
+
Change to a different branch
+
git checkout differentbranch
+
Merge a branch to current active branch
+
git merge somebranch
+
Delete a branch
+
git branch -d somebranch
+
Push a local branch or tag to a remote repository
+
git push REMOTENAME BRANCHNAME
+
Delete a branch or tag in a remote repository
+
git push REMOTENAME :BRANCHNAME
+
Diff between two branches
+
git diff master..somebranch
+
Diff between two commit IDs (found in git log)
+
git diff e9780c7cba2855350e914fde227a79bb63c1351d..8b014e40346b38b3b9bfc41359b4e8a68e804c0d
+
Diff between the last two commits
+
git diff HEAD^ HEAD
+
Patchset between two branches (follows same syntax as git diff afaik)
+
git format-patch master..somebranch
+
Or better: http://wiki.winehq.org/GitWine#head-f7a29e7ed999b5924748a60c5a1cd4a019032d26
+
git format-patch -o out origin
+
Set [[nano]] as default editor
+
git config --global core.editor "nano -w"
+
  
==Git Prompt==
+
will clone a Git repository in a new directory inside your current directory. Leaving out {{ic|<dir>}}
Git package comes with a bash completion file. This file, also contains the necessary functions to provide git information on your bash or zsh shell prompt. To enable it add {{Ic|$(__git_ps1 " (%s)")}} to you PS1 variable.
+
will cause it to name the folder after the Git repository. For example,
* For bash:
+
 
 +
git clone git@github.com:torvalds/linux.git
 +
 
 +
clones Github's mirror of the Linux kernel into a directory named "linux".
 +
 
 +
===提交(commit)文件到版本库===
 +
 
 +
Git's commit process involves two steps:
 +
 
 +
# Add new files, add changes for existing files (both with {{ic|git add <files>}}), and/or remove files (with {{ic|git rm}}). These changes are put in a staging area called the index.
 +
# Call {{ic|git commit}} to commit the changes.
 +
 
 +
Git commit will open up a text editor to provide a commit message.
 +
You can set this editor to whatever you want by changing the {{ic|core.editor}} option with {{ic|git config}}.
 +
 
 +
Alternatively, you can use {{ic|git commit -m <message>}} to supply the commit message without opening the text editor.
 +
 
 +
Other useful commit tricks:
 +
 
 +
{{ic|git commit -a}} lets you commit changes you have made to files already under Git control
 +
without having to take the step of adding the changes to the index. You still have to add new files with git add.
 +
 
 +
{{ic|git add -p}} lets you commit specific parts of files you have changed.
 +
This is useful if you have made a bunch of changes that you think would be best split into several commits.
 +
 
 +
===将改动提交(push)到公共版本库===
 +
 
 +
To push your changes up to a server (such as Github), use
 +
 
 +
git push <server name> <branch>
 +
 
 +
Adding {{ic|-u}} will make this server the default one to push to for this branch.
 +
If you have cloned the repository as described above, the server will default to the location you cloned the
 +
repository from (nicknamed "origin") and the branch will default to the master branch.
 +
In other words, if you have followed this guide's instructions in cloning, {{ic|git push}} will suffice.
 +
You can set up Git to push to multiple servers if you want, but that is a more advanced topic.
 +
Branches will be discussed later in this guide.
 +
 
 +
===从服务器公共版本库下载修改===
 +
 
 +
If you are working on multiple machines and want to update your local repository to what the server has, you use
 +
 
 +
git pull <server name> <branch>
 +
 
 +
Similarly to push, the server name and branch should have sane defaults, so {{ic|git pull}} should suffice.
 +
Git pull is actually shorthand for doing two things:
 +
 
 +
# Calling {{ic|git fetch}}, which updates the local copy of what the server has. Such branches are called "remote" branches because they are mirroring remote servers.
 +
# Calling {{ic|git merge}}, which merges what the remote branch has with what you have. If your commit history is the same as the server's commit history, you will be automatically fast-forwarded to the latest commit on the server. If your history does not match (maybe someone else has pushed commits since you last synced), the two histories will be merged.
 +
 
 +
It is not a bad idea to get into the practice of using these two commands instead of {{ic|git pull}}. This way you can
 +
check to make sure that the server contains what you would expect before merging.
 +
 
 +
===查看历史记录===
 +
 
 +
The command {{ic|git log}} shows the history of your current branch. Note that each commit is identified by a SHA-1 hash.
 +
The author, commit date, and commit message follow. A more useful command is
 +
 
 +
git log --graph --oneline --decorate
 +
 
 +
which provides a display similar to TortoiseGit's log window. It shows the following:
 +
 
 +
* The first 7 digits of each commit's SHA-1 hash (enough to be unique)
 +
* The {{ic|--graph}} option shows how any branches (if there are others) fork off from the current branch.
 +
* The {{ic|--oneline}} option shows only the first line of each commit message
 +
* The {{ic|--decorate}} option shows all commit labels (branches and tags)
 +
 
 +
It may be convenient to alias this command as {{ic|git graph}} by doing the following:
 +
 
 +
git config --global alias.graph 'log --graph --oneline --decorate'
 +
 
 +
Now typing {{ic|git graph}} will run {{ic|git log --graph --oneline --decorate}}.
 +
{{ic|git graph}} and {{ic|git log}} may be given the {{ic|--all}} flag in order to view all branches instead of just the current one.
 +
Adding {{ic|--stat}} to one of these commands is also useful -
 +
it shows which files each commit changed and how many lines were changed in each file.
 +
 
 +
===处理合并===
 +
 
 +
Merges happen when you pull, as a result of a rebase operation, and when you merge one branch into another.
 +
Like other version control tools, when Git cannot automatically merge a commit, it turns to you.
 +
See [http://git-scm.com/book/en/Git-Branching-Basic-Branching-and-Merging#Basic-Merge-Conflicts this section]
 +
of the Git Book for an explanation on how to resolve merge conflicts.
 +
If you screw up and would like to back out of the merge, you can usually abort the merge using the {{ic|--abort}} flag
 +
with whatever command started the merge (e.g. {{ic|git merge --abort}}, {{ic|git pull --abort}}, {{ic|git rebase --abort}}).
 +
 
 +
==使用分布式版本控制系统==
 +
 
 +
The above commands only provide the basics.
 +
The real power and convenience in Git (and other distributed version control systems) come from leveraging its local commits and fast branching.
 +
A typical Git workflow looks like this:
 +
 
 +
# Create and check out a branch to add a feature.
 +
# Make as many commits as you would like on that branch while developing that feature.
 +
# Squash, rearrange, and edit your commits until you are satisfied with the commits enough to push them to the central server and make them public.
 +
# Merge your branch back into the main branch.
 +
# Delete your branch, if you desire.
 +
# Push your changes to the central server.
 +
 
 +
===创建一个分支===
 +
 
 +
git branch <branch name>
 +
 
 +
can be used to create a branch that will branch off the current commit.
 +
After it has been created, you should switch to it using
 +
 
 +
git checkout <branch name>
 +
 
 +
A simpler method is to do both in one step with
 +
 
 +
git checkout -b <branch name>
 +
 
 +
To see a list of branches, and which branch is currently checked out, use
 +
 
 +
git branch
 +
 
 +
===A word on commits===
 +
 
 +
Many of the following commands take commits as arguments. A commit can be identified by any of the following:
 +
 
 +
* Its 40-digit SHA-1 hash (the first 7 digits are usually sufficient to identify it uniquely)
 +
* Any commit label such as a branch or tag name
 +
* The label {{ic|HEAD}} always refers to the currently checked-out commit (usually the head of the branch, unless you used {{ic|git checkout}} to jump back in history to an old commit)
 +
* Any of the above plus {{ic|~}} to refer to previous commits. For example, {{ic|HEAD~}} refers to one commit before {{ic|HEAD}} and {{ic|HEAD~5}} refers to five commits before {{ic|HEAD}}.
 +
 
 +
===提交为检查点===
 +
 
 +
In Subversion and other older, centralized version control systems, commits are permanent - once you make them,
 +
they are there on the server for everyone to see.
 +
In Git, your commits are local and you can combine, rearrange, and edit them before pushing them to the server.
 +
This gives you more flexibility and lets you use commits as checkpoints. Commit early and commit often.
 +
 
 +
===编辑之前的提交===
 +
 
 +
git commit --amend
 +
 
 +
allows you to modify the previous commit. The contents of the index will be applied to it,
 +
allowing you to add more files or changes you forgot to put in. You can also use it to edit the commit message,
 +
if you would like.
 +
 
 +
===插入、重新排序和更改历史记录===
 +
 
 +
git rebase -i <commit>
 +
 
 +
will bring up a list of all commits between {{ic|<commit>}} and the present, including {{ic|HEAD}} but excluding {{ic|<commit>}}.
 +
This command allows you rewrite history. To the left of each commit, a command is specified.
 +
Your options are as follows:
 +
 
 +
* The "pick" command (the default) uses that commit in the rewritten history.
 +
* The "reword" command lets you change a commit message without changing the commit's contents.
 +
* The "edit" command will cause Git to pause during the history rewrite at this commit. You can then modify it with {{ic|git commit --amend}} or insert new commits.
 +
* The "squash" command will cause a commit to be folded into the previous one. You will be prompted to enter a message for the combined commit.
 +
* The "fixup" command works like squash, but discards the message of the commit being squashed instead of prompting for a new message.
 +
* Commits can be erased from history by deleting them from the list of commits
 +
* Commits can be re-ordered by re-ordering them in the list. When you are done modifying the list, Git will prompt you to resolve any resulting merge problems (after doing so, continue rebasing with {{ic|git rebase --continue}})
 +
 
 +
When you are done modifying the list, Git will perform the desired actions.
 +
If Git stops at a commit (due to merge conflicts caused by re-ordering the commits or due to the "edit" command),
 +
use {{ic|git rebase --continue}} to resume. You can always back out of the rebase operation with {{ic|git rebase --abort}}.
 +
 
 +
{{warning|Only use {{ic|git rebase -i}} on local commits that have not yet been pushed to anybody else.
 +
Modifying commits that are on the central server will cause merge problems for obvious reasons.}}
 +
 
 +
{{note|Vim makes these rebase operations very simple since lines can be cut and pasted with few keystrokes.}}
 +
 
 +
==Git提示符==
 +
The Git package comes with a prompt script. To enable the prompt addition you will need to source the git-prompt.sh script and add {{Ic|$(__git_ps1 " (%s)")}} to you PS1 variable.
 +
* Copy {{Ic|/usr/share/git/completion/git-prompt.sh}} to your home directory (e.g. {{Ic|~/.git-prompt.sh}}).
 +
* Add the following line to your .bashrc/.zshrc:
 +
source ~/.git-prompt.sh
 +
* For Bash:
 
  PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
 
  PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
 +
{{Note|For information about coloring your bash prompt see [[Color_Bash_Prompt]]}}
 +
 
* For zsh:
 
* For zsh:
 
  PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '
 
  PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '
Line 97: Line 238:
 
|}
 
|}
  
In addition you can set the {{Ic|GIT_PS1_SHOWUPSTREAM}} variable to {{Ic|"auto"}} in order to see {{Ic|'''<'''}} if you are behind upstream, {{Ic|'''>'''}} if you are ahead and {{Ic|'''<>'''}} if you have diverged.
+
==传输协议==
 +
===智能HTTP===
 +
Since version 1.6.6 git is able to use the HTTP(S) protocol as efficiently as SSH or Git by utilizing the git-http-backend. Furthermore it is not only possible to clone or pull from repositories, but also to push into repositories over HTTP(S).
  
{{Note|If you don't use bash completion consider sourcing '''''/usr/share/git/completion/git-completion.bash''''' in your '''.bashrc'''/'''.zshrc'''}}
+
The setup for this is rather simple as all you need to have installed is the Apache web server (with mod_cgi, mod_alias, and mod_env enabled) and of course, git:
 
+
==Transfer Protocols==
+
===Smart HTTP===
+
Since version 1.6.6 git is able to use the HTTP(S) protocol as efficiently as SSH or GIT by utilizing the git-http-backend. Furthermore it is not only possible to clone or pull from repositories, but also to push into repositories over HTTP(S).
+
 
+
The setup for this is rather simple as all you need to have installed is the Apache webserver (with mod_cgi, mod_alias, and mod_env enabled) and of course, git:
+
 
  # pacman -S apache git
 
  # pacman -S apache git
  
Line 124: Line 261:
 
For more detailed documentation, visit the following links:
 
For more detailed documentation, visit the following links:
 
* http://progit.org/2010/03/04/smart-http.html
 
* http://progit.org/2010/03/04/smart-http.html
* http://www.kernel.org/pub/software/scm/git/docs/git-http-backend.html{{Linkrot|2012|01|26}}
+
* https://www.kernel.org/pub/software/scm/git/docs/v1.7.10.1/git-http-backend.html
  
 
===Git SSH===
 
===Git SSH===
You first need to have a public SSH key. For that follow the guide at [[Using SSH Keys]]. To setup SSH itself you need to follow the [[SSH]] guide. I assume you have a public SSH key now and your SSH is working.
+
You first need to have a public SSH key. For that follow the guide at [[Using SSH Keys]]. To set up SSH itself, you need to follow the [[SSH]] guide. This assumes you have a public SSH key now and that your SSH is working.
Open your SSH key in your favorite editor (default public key name is id_rsa.pub and is located in {{ic|~/.ssh}}) and copy its content (CTRL + C).
+
Open your SSH key in your favorite editor (default public key name is {{ic|~/.ssh/id_rsa.pub}}), and copy its content ({{keypress|Ctrl+c}}).
Now go to your user where you have made your git repository, since we now need to allow that SSH key to login on that user to access the GIT repository.
+
Now go to your user where you have made your Git repository, since we now need to allow that SSH key to log in on that user to access the Git repository.
Open this file in your favorite editor (i use nano)
+
Open {{ic|~/.ssh/authorized_keys}} in your favorite editor, and paste the contents of id_rsa.pub in it. Be sure it is all on one line! That is important! It should look somewhat like this:
nano ~/.ssh/authorized_keys
+
and paste the contents of id_rsa.pub in it. Be sure it is all on one line! That is important! It should look somewhat like this:
+
 
{{Warning|Do not copy the line below! It is an example! It will not work if you use that line!}}
 
{{Warning|Do not copy the line below! It is an example! It will not work if you use that line!}}
 
<pre style='overflow:auto'>
 
<pre style='overflow:auto'>
 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCboOH6AotCh4OcwJgsB4AtXzDo9Gzhl+BAHuEvnDRHNSYIURqGN4CrP+b5Bx/iLrRFOBv58TcZz1jyJ2PaGwT74kvVOe9JCCdgw4nSMBV44cy+6cTJiv6f1tw8pHRS2H6nHC9SCSAWkMX4rpiSQ0wkhjug+GtBWOXDaotIzrFwLw== username@hostname
 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCboOH6AotCh4OcwJgsB4AtXzDo9Gzhl+BAHuEvnDRHNSYIURqGN4CrP+b5Bx/iLrRFOBv58TcZz1jyJ2PaGwT74kvVOe9JCCdgw4nSMBV44cy+6cTJiv6f1tw8pHRS2H6nHC9SCSAWkMX4rpiSQ0wkhjug+GtBWOXDaotIzrFwLw== username@hostname
 
</pre>
 
</pre>
Now you can checkout your git repo this way (change where needed. Here it is using the git username and localhost):
+
Now you can checkout your Git repository this way (change where needed. Here it is using the git username and localhost):
 
  git clone git@localhost:my_repository.git
 
  git clone git@localhost:my_repository.git
You should now get an SSH yes/no question. Type yes followed by enter. Then you should have your repository checked out. Since this is with SSH you also do have commit rights now. For that look at [[Git]] and [[Super Quick Git Guide]].
+
You should now get an SSH yes/no question. Type {{ic|yes}} followed by {{keypress|Enter}}. Then you should have your repository checked out. Because this is with SSH, you also do have commit rights now. For that look at [[Git]] and [[Super Quick Git Guide]].
  
====Specifying a non-standard port====
+
====特定非标准端口====
Connecting on a port other than 22 can be configured on a per-host basis in {{ic|/etc/ssh/ssh_config}} or {{ic|~/.ssh/config}}. To set up ports for a repository, specify the path in {{ic|.git/config}} using the port number ''N'' and the '''absolute path''' ''/PATH/TO/REPO'':
+
Connecting on a port other than 22 can be configured on a per-host basis in {{ic|/etc/ssh/ssh_config}} or {{ic|~/.ssh/config}}. To set up ports for a repository, specify the path in {{ic|.git/config}} using the port number {{ic|N}} and the ''absolute path'' {{ic|/PATH/TO/REPO}}:
 
  ssh://user@example.org:N/PATH/TO/REPO
 
  ssh://user@example.org:N/PATH/TO/REPO
 
Typically the repository resides in the home directory of the user which allows you to use tilde-expansion. Thus to connect on port N=443,
 
Typically the repository resides in the home directory of the user which allows you to use tilde-expansion. Thus to connect on port N=443,
Line 149: Line 284:
 
  url = ssh://git@example.org:443/~git/repo.git
 
  url = ssh://git@example.org:443/~git/repo.git
  
===GIT Daemon===
+
===Git守护进程===
 
{{Note|The git daemon only allows read access. For write access see [[#Git SSH]].}}
 
{{Note|The git daemon only allows read access. For write access see [[#Git SSH]].}}
 
This will allow URLs like "git clone git://localhost/my_repository.git".
 
This will allow URLs like "git clone git://localhost/my_repository.git".
  
Edit configuration file for git-dameon {{ic|/etc/conf.d/git-daemon.conf}} (GIT_REPO is a place with your git projects), then start git-daemon with root privileges:
+
Edit the configuration file for git-daemon {{ic|/etc/conf.d/git-daemon.conf}} (GIT_REPO is a place with your git projects), then start git-daemon with root privileges:
  # /etc/rc.d/git-daemon start
+
  # systemctl start git-daemon@
  
To run the git-daemon every time at boot, just append {{Ic|git-daemon}} to {{Ic|DAEMONS}} line in [[rc.conf]].
+
To run the git-daemon every time at boot, enable the service:
 +
# systemctl enable git-daemon@
  
 
Clients can now simply use:
 
Clients can now simply use:
 
  git clone git://localhost/my_repository.git
 
  git clone git://localhost/my_repository.git
  
=== GIT repositories rights ===
+
===Git版本库权限===
 
To restrict read/write access, you can simply use Unix rights, see http://sitaramc.github.com/gitolite/doc/overkill.html
 
To restrict read/write access, you can simply use Unix rights, see http://sitaramc.github.com/gitolite/doc/overkill.html
  
 
For a fine-grained rights access, see [[gitolite]] and [[gitosis]]
 
For a fine-grained rights access, see [[gitolite]] and [[gitosis]]
  
==References==
+
==参见==
* http://www.kernel.org/pub/software/scm/git/docs/
+
 
* http://book.git-scm.com/index.html
 
* http://book.git-scm.com/index.html
 
* http://gitref.org/
 
* http://gitref.org/
 +
* http://www.kernel.org/pub/software/scm/git/docs/
 
* http://help.github.com/
 
* http://help.github.com/

Revision as of 07:57, 13 April 2013

Tango-preferences-desktop-locale.png本页面需要更新翻译,内容可能已经与英文脱节。要贡献翻译,请访问简体中文翻译组Tango-preferences-desktop-locale.png

附注: please use the first argument of the template to provide more detailed indications.
摘要 help replacing me
安装和使用 Git 版本管理系统
相关页面
Super Quick Git Guide: Generally about contributing to pacman, although it still serves as a practical Git tutorial
Gitweb
Cgit
Subversion
Concurrent Versions System
github

Git 是一个 Linus Torvalds 编写的版本控制系统 (VCS),现在被用来维护 Linux 内核以及数以千计的其他项目,包括 Pacman(Arch 的软件包管理器)

有一个很全面的文档,包含了手册和教程,可以从 官方网站 获得。

安装

git 可以用 Pacman 从 [extra] 仓库安装。如果你关心使用 Git 配合其他的 VCS 软件,邮件服务器,或者使用 Git 的图形界面,注意看可选的依赖。

Bash 自动完成 (例如,按 tab 来完成你正在键入的命令),只需要:

source /usr/share/git/completion/git-completion.bash

另外,你可以安装 bash-completion 软件包来自动为新的外壳加载自动完成。

如果你想使用 Git 内建的图形界面 (例如 gitk 或者 git gui) 你需要安装 tk 软件包,否则你会遇到一个隐晦的错误信息:

/usr/bin/gitk: line 3: exec: wish: not found.

配置

Git 从几个 INI 格式的配置文件中读取配置信息。在每一个 git 仓库中 .git/config 被用来指定与本仓库有关的配置选项。每一个用户 ("global") 的配置文件在 $HOME/.gitconfig 被用来作为仓库配置的备用配置。你也可以直接编辑文件,但是更推荐的方法是使用 git-config 工具。例如,

$ git config --global core.editor "nano -w"

会添加 editor = nano -w~/.gitconfig 文件的 [core] 部分中。

git-config 工具的 man page 有一个很长的参数列表,列出所以可以设置的变量。

这是一些你可能用到的常见的配置:

$ git config --global user.name "Firstname Lastname"
$ git config --global user.email "your_email@youremail.com"
$ git config --global color.ui true
$ git config --global --list

基本用法

克隆一个版本库

git clone <repo location> <dir>

will clone a Git repository in a new directory inside your current directory. Leaving out <dir> will cause it to name the folder after the Git repository. For example,

git clone git@github.com:torvalds/linux.git

clones Github's mirror of the Linux kernel into a directory named "linux".

提交(commit)文件到版本库

Git's commit process involves two steps:

  1. Add new files, add changes for existing files (both with git add <files>), and/or remove files (with git rm). These changes are put in a staging area called the index.
  2. Call git commit to commit the changes.

Git commit will open up a text editor to provide a commit message. You can set this editor to whatever you want by changing the core.editor option with git config.

Alternatively, you can use git commit -m <message> to supply the commit message without opening the text editor.

Other useful commit tricks:

git commit -a lets you commit changes you have made to files already under Git control without having to take the step of adding the changes to the index. You still have to add new files with git add.

git add -p lets you commit specific parts of files you have changed. This is useful if you have made a bunch of changes that you think would be best split into several commits.

将改动提交(push)到公共版本库

To push your changes up to a server (such as Github), use

git push <server name> <branch>

Adding -u will make this server the default one to push to for this branch. If you have cloned the repository as described above, the server will default to the location you cloned the repository from (nicknamed "origin") and the branch will default to the master branch. In other words, if you have followed this guide's instructions in cloning, git push will suffice. You can set up Git to push to multiple servers if you want, but that is a more advanced topic. Branches will be discussed later in this guide.

从服务器公共版本库下载修改

If you are working on multiple machines and want to update your local repository to what the server has, you use

git pull <server name> <branch>

Similarly to push, the server name and branch should have sane defaults, so git pull should suffice. Git pull is actually shorthand for doing two things:

  1. Calling git fetch, which updates the local copy of what the server has. Such branches are called "remote" branches because they are mirroring remote servers.
  2. Calling git merge, which merges what the remote branch has with what you have. If your commit history is the same as the server's commit history, you will be automatically fast-forwarded to the latest commit on the server. If your history does not match (maybe someone else has pushed commits since you last synced), the two histories will be merged.

It is not a bad idea to get into the practice of using these two commands instead of git pull. This way you can check to make sure that the server contains what you would expect before merging.

查看历史记录

The command git log shows the history of your current branch. Note that each commit is identified by a SHA-1 hash. The author, commit date, and commit message follow. A more useful command is

git log --graph --oneline --decorate

which provides a display similar to TortoiseGit's log window. It shows the following:

  • The first 7 digits of each commit's SHA-1 hash (enough to be unique)
  • The --graph option shows how any branches (if there are others) fork off from the current branch.
  • The --oneline option shows only the first line of each commit message
  • The --decorate option shows all commit labels (branches and tags)

It may be convenient to alias this command as git graph by doing the following:

git config --global alias.graph 'log --graph --oneline --decorate'

Now typing git graph will run git log --graph --oneline --decorate. git graph and git log may be given the --all flag in order to view all branches instead of just the current one. Adding --stat to one of these commands is also useful - it shows which files each commit changed and how many lines were changed in each file.

处理合并

Merges happen when you pull, as a result of a rebase operation, and when you merge one branch into another. Like other version control tools, when Git cannot automatically merge a commit, it turns to you. See this section of the Git Book for an explanation on how to resolve merge conflicts. If you screw up and would like to back out of the merge, you can usually abort the merge using the --abort flag with whatever command started the merge (e.g. git merge --abort, git pull --abort, git rebase --abort).

使用分布式版本控制系统

The above commands only provide the basics. The real power and convenience in Git (and other distributed version control systems) come from leveraging its local commits and fast branching. A typical Git workflow looks like this:

  1. Create and check out a branch to add a feature.
  2. Make as many commits as you would like on that branch while developing that feature.
  3. Squash, rearrange, and edit your commits until you are satisfied with the commits enough to push them to the central server and make them public.
  4. Merge your branch back into the main branch.
  5. Delete your branch, if you desire.
  6. Push your changes to the central server.

创建一个分支

git branch <branch name>

can be used to create a branch that will branch off the current commit. After it has been created, you should switch to it using

git checkout <branch name>

A simpler method is to do both in one step with

git checkout -b <branch name>

To see a list of branches, and which branch is currently checked out, use

git branch

A word on commits

Many of the following commands take commits as arguments. A commit can be identified by any of the following:

  • Its 40-digit SHA-1 hash (the first 7 digits are usually sufficient to identify it uniquely)
  • Any commit label such as a branch or tag name
  • The label HEAD always refers to the currently checked-out commit (usually the head of the branch, unless you used git checkout to jump back in history to an old commit)
  • Any of the above plus ~ to refer to previous commits. For example, HEAD~ refers to one commit before HEAD and HEAD~5 refers to five commits before HEAD.

提交为检查点

In Subversion and other older, centralized version control systems, commits are permanent - once you make them, they are there on the server for everyone to see. In Git, your commits are local and you can combine, rearrange, and edit them before pushing them to the server. This gives you more flexibility and lets you use commits as checkpoints. Commit early and commit often.

编辑之前的提交

git commit --amend

allows you to modify the previous commit. The contents of the index will be applied to it, allowing you to add more files or changes you forgot to put in. You can also use it to edit the commit message, if you would like.

插入、重新排序和更改历史记录

git rebase -i <commit>

will bring up a list of all commits between <commit> and the present, including HEAD but excluding <commit>. This command allows you rewrite history. To the left of each commit, a command is specified. Your options are as follows:

  • The "pick" command (the default) uses that commit in the rewritten history.
  • The "reword" command lets you change a commit message without changing the commit's contents.
  • The "edit" command will cause Git to pause during the history rewrite at this commit. You can then modify it with git commit --amend or insert new commits.
  • The "squash" command will cause a commit to be folded into the previous one. You will be prompted to enter a message for the combined commit.
  • The "fixup" command works like squash, but discards the message of the commit being squashed instead of prompting for a new message.
  • Commits can be erased from history by deleting them from the list of commits
  • Commits can be re-ordered by re-ordering them in the list. When you are done modifying the list, Git will prompt you to resolve any resulting merge problems (after doing so, continue rebasing with git rebase --continue)

When you are done modifying the list, Git will perform the desired actions. If Git stops at a commit (due to merge conflicts caused by re-ordering the commits or due to the "edit" command), use git rebase --continue to resume. You can always back out of the rebase operation with git rebase --abort.

Warning: Only use git rebase -i on local commits that have not yet been pushed to anybody else. Modifying commits that are on the central server will cause merge problems for obvious reasons.
Note: Vim makes these rebase operations very simple since lines can be cut and pasted with few keystrokes.

Git提示符

The Git package comes with a prompt script. To enable the prompt addition you will need to source the git-prompt.sh script and add $(__git_ps1 " (%s)") to you PS1 variable.

  • Copy /usr/share/git/completion/git-prompt.sh to your home directory (e.g. ~/.git-prompt.sh).
  • Add the following line to your .bashrc/.zshrc:
source ~/.git-prompt.sh
  • For Bash:
PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
Note: For information about coloring your bash prompt see Color_Bash_Prompt
  • For zsh:
PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '

The %s is replaced by the current branch name. The git information is displayed only if you are navigating in a git repository. You can enable extra information by setting and exporting certain variables to a non-empty value as shown in the following table:

Variable Information
GIT_PS1_SHOWDIRTYSTATE * for unstaged and + for staged changes
GIT_PS1_SHOWSTASHSTATE $ if something is stashed
GIT_PS1_SHOWUNTRACKEDFILES % if there are untracked files

传输协议

智能HTTP

Since version 1.6.6 git is able to use the HTTP(S) protocol as efficiently as SSH or Git by utilizing the git-http-backend. Furthermore it is not only possible to clone or pull from repositories, but also to push into repositories over HTTP(S).

The setup for this is rather simple as all you need to have installed is the Apache web server (with mod_cgi, mod_alias, and mod_env enabled) and of course, git:

# pacman -S apache git

Once you have your basic setup up and running, add the following to your Apache's config usually located at /etc/httpd/conf/httpd.conf:

<Directory "/usr/lib/git-core*">
    Order allow,deny
    Allow from all
</Directory>

SetEnv GIT_PROJECT_ROOT /srv/git
SetEnv GIT_HTTP_EXPORT_ALL
ScriptAlias /git/ /usr/lib/git-core/git-http-backend/

The above example config assumes that your git repositories are located at /srv/git and that you want to access them via something like http(s)://your_address.tld/git/your_repo.git. Feel free to customize this to your needs.

Note: Of course you have to make sure that your Apache can read and write (if you want to enable push access) on your git repositories.

For more detailed documentation, visit the following links:

Git SSH

You first need to have a public SSH key. For that follow the guide at Using SSH Keys. To set up SSH itself, you need to follow the SSH guide. This assumes you have a public SSH key now and that your SSH is working. Open your SSH key in your favorite editor (default public key name is ~/.ssh/id_rsa.pub), and copy its content (Template:Keypress). Now go to your user where you have made your Git repository, since we now need to allow that SSH key to log in on that user to access the Git repository. Open ~/.ssh/authorized_keys in your favorite editor, and paste the contents of id_rsa.pub in it. Be sure it is all on one line! That is important! It should look somewhat like this:

Warning: Do not copy the line below! It is an example! It will not work if you use that line!
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCboOH6AotCh4OcwJgsB4AtXzDo9Gzhl+BAHuEvnDRHNSYIURqGN4CrP+b5Bx/iLrRFOBv58TcZz1jyJ2PaGwT74kvVOe9JCCdgw4nSMBV44cy+6cTJiv6f1tw8pHRS2H6nHC9SCSAWkMX4rpiSQ0wkhjug+GtBWOXDaotIzrFwLw== username@hostname

Now you can checkout your Git repository this way (change where needed. Here it is using the git username and localhost):

git clone git@localhost:my_repository.git

You should now get an SSH yes/no question. Type yes followed by Template:Keypress. Then you should have your repository checked out. Because this is with SSH, you also do have commit rights now. For that look at Git and Super Quick Git Guide.

特定非标准端口

Connecting on a port other than 22 can be configured on a per-host basis in /etc/ssh/ssh_config or ~/.ssh/config. To set up ports for a repository, specify the path in .git/config using the port number N and the absolute path /PATH/TO/REPO:

ssh://user@example.org:N/PATH/TO/REPO

Typically the repository resides in the home directory of the user which allows you to use tilde-expansion. Thus to connect on port N=443,

url = git@example.org:repo.git

becomes:

url = ssh://git@example.org:443/~git/repo.git

Git守护进程

Note: The git daemon only allows read access. For write access see #Git SSH.

This will allow URLs like "git clone git://localhost/my_repository.git".

Edit the configuration file for git-daemon /etc/conf.d/git-daemon.conf (GIT_REPO is a place with your git projects), then start git-daemon with root privileges:

# systemctl start git-daemon@

To run the git-daemon every time at boot, enable the service:

# systemctl enable git-daemon@

Clients can now simply use:

git clone git://localhost/my_repository.git

Git版本库权限

To restrict read/write access, you can simply use Unix rights, see http://sitaramc.github.com/gitolite/doc/overkill.html

For a fine-grained rights access, see gitolite and gitosis

参见