Git的用法

git上传项目到github示意图:

git图示

  • Workspace:工作区
  • Index / Stage:暂存区
  • Repository:仓库区(或本地仓库)
  • Remote:远程仓库

安装

Ubuntuapt-get install git

常用命令

  1. 初始化(init)

    1
    2
    # 初始化项目,切换到项目目录,执行下面操作
    $ git init
  2. 配置(config)

    1
    2
    3
    4
    5
    # 设置提交代码时的用户信息
    $ git config [--global] user.email 你的邮箱
    $ git config [--global] user.name 你的用户名
    # 显示当前的git配置
    $ git config --list
  3. 状态(status)

    1
    2
    # 显示状态信息,包括文件修改,文件提交等信息
    $ git status
  4. 添加(add)/删除(rm)

    1
    2
    3
    4
    5
    6
    # 将文件添加到暂存区(Index / Stage)
    $ git add hello.c
    # 将当前项目下的所有文件添加到暂存区(Index / Stage)
    $ git add .
    # 删除工作区(Workspace)文件,并且将这次删除的文件放入暂存区(Index / Stage)
    $ git rm hello.c
  5. 代码提交(commit)

    1
    2
    # 提交暂存区到仓库区
    $ git commit -m [备注]
  6. 上传远程(push)

    1
    2
    # 上传本地指定分支到远程仓库
    $ git push [remote] [branch]
  7. 撤销(checkout)

    1
    2
    3
    4
    5
    6
    # 恢复暂存区(Index / Stage)的指定文件到工作区(Workspace)
    $ git checkout [file]
    # 恢复摸个commit的指定文件到暂存区和工作区
    $ git checkout [commit] [file]
    # 恢复暂存区的所有文件到工作区
    $ git checkout

使用Git上传本地项目到github上

  1. 安装git

    1
    $ apt-get install git
  2. 配置

    1
    2
    $ git config --global user.name "用户名"
    $ git config --global user.email "邮箱"
  3. 生成密钥

    1
    2
    3
    4
    5
    # 切换到用户目录
    $ cd ~
    # 生成密钥
    $ ssh-keygen -t rsa -C "邮箱"
    $ cd .ssh

    复制id_rsa.pub文件内容,在github中Settings选项中SSH and GPG keys选项,右侧点击 New SSH key,将idb_rsa.pub中的内容复制到Key中,Title随便填

  4. 将本地项目上传到Github

    切换到项目目录下

    1
    2
    3
    4
    5
    6
    # 初始化项目
    $ git init
    # 添加项目下所有文件到暂存区(Index / Stage)
    $ git add .
    # 将暂存区文件提交到本地仓库
    $ git commit -m "这是备注"

    关联Github上创建的仓库

    管理Github

    1
    $ git remote add origin xxxxxxxxxx(这里输入github仓库地址)

    将本地仓库文件上传到远程Github仓库

    1
    $ git push origin [branch]

参考:

http://www.ruanyifeng.com/blog/2015/12/git-cheat-sheet.html

https://www.cnblogs.com/sdcs/p/8270029.html