Mac 下 git 的最基础入门

安装

使用 Homebrew 安装

在 Terminal 中执行

1
$ brew install git

设置提交者信息

首先需要设定你的用户名和电子邮件地址

1
2
$ git config --global user.name "<用户名>"
$ git config --global user.email "<电子邮件>"

新建本地数据库

终端切换到要进行版本管理的目录,执行 init 命令

1
2
$ git init
Initialized empty Git repository in /Users/wangxuan/tutorial/.git/

提交文件

在目录下新建一个文件,然后用 status 命令确认目录状态

1
2
3
4
5
6
7
8
9
10
11
$git status
On branch master

Initial commit

Untracked files:
(use "git add <file>..." to include in what will be committed)

sample.txt

nothing added to commit but untracked files present (use "git add" to track)

提示信息说明 sample.txt 文件不是历史记录对象的文件(即被修改过)

这时需要使用 add 命令将其添加到索引

1
$git add <filename>

注:当 <filename> 设定为 . 时即代表把所有的文件加入到索引

1
2
3
4
5
6
7
8
9
10
$ git add sample.txt
$ git status
On branch master

Initial commit

Changes to be committed:
(use "git rm --cached <file>..." to unstage)

new file: sample.txt

接下来执行 commit 命令提交

1
$ git commit -m "提交说明"

提交后确认状态

1
2
3
4
5
6
7
$ git commit -m "first commit"
[master (root-commit) 5b770fe] first commit
1 file changed, 1 insertion(+)
create mode 100644 sample.txt
$ git status
On branch master
nothing to commit, working tree clean

最后,确认下数据库的提交记录。要显示数据库的提交记录可以使用 log 命令。

1
2
3
4
5
6
$ git log
commit 5b770feedc27b3739af98ce1bed4ac1fcc8a54cb
Author: Singee <[email protected]>
Date: Fri Feb 3 14:23:04 2017 +0800

first commit

push 到远程数据库

添加远程数据库,可以使用 remote 指令。 <name> 是注册名称,<.git url> 是指定远程数据库的 URL (通常以 .git 结尾)。

1
$ git remote add <name> <.git url>

通过运行以下指令,将创建于上一个页面的远程数据库的 URL 以 “origin” 命名注册。

用 origin 的名称登录远程数据库的URL

1
$ git remote add origin <.git url>

向数据库推送,可以使用 push 命令。<repository> 是推送的目标地址,<refspec> 是指定推送的分支。在高级篇将更详细地对分支进行说明。

1
$ git push <repository> <refspec>

运行以下命令便可向推远程数据库 origin 进行推送。如果指定了 -u 运行选项,下一次开始就可以省略其后的分支名称。但是,首次运行指令向远程数据库推送时,不能省略远程数据库名称或分支名称。

其间可能会请求用户名和密码,请输入您有权限进行 push 操作的用户名和密码。

1
2
3
4
5
6
7
8
9
$ git push -u origin master
Username for '...': <这里需要输入用户名>
Password for '...': <这里需要输入密码,输入无回显>
Counting objects: 3, done.
Writing objects: 100% (3/3), 241 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To <.git url>
* [new branch] master -> master
Branch master set up to track remote branch master from origin.

clone 远程数据库

使用 clone 指令可以复制数据库,<repository> 指定为远程数据库的 URL,<directory> 指定为复制目标目录的名称。

1
$ git clone <repository> <directory>

执行以下指令后,当前目录下会以 tutorial2 为目录名复制远程数据库。

1
2
3
4
5
$ git clone <.git url> tutorial2
Cloning into 'tutorial2'...
remote: Counting objects: 3, done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.

从远程数据库 pull

为了进行拉送 pull 操作,使用 pull 指令。省略数据库名称的话,会对名为 origin 的数据库进行 pull (即合并到本地)。

1
$ git pull <repository> <refspec>...

其他

更加详细的内容请看 猴子都能懂的 git 入门