Git常用命令整理

360 阅读2分钟

使用ssh-key

# 生成ssh key
ssh-keygen -t rsa -C 'email'
cat ~/.ssh/id_rsa.pub
# mac: 
pbcopy < ~/.ssh/id_rsa.pub 
# windows: 
cat ~/.ssh/id_rsa.pub | clip || type %userprofile%\.ssh\id_rsa.pub | clip
# Linux: 
xclip -sel clib < ~/.ssh/id_rsa.pub

仓库管理

# 创建本地仓库
mkdir repository
cd repository 
git init
# 创建远程仓库
# 进入本地仓库根目录,将本地仓库与远程仓库关联(以GitHub为例)
git remote add origin url
# 推送本地仓库数据到远程仓库
git push -u origin master
从远程仓库克隆项目
git clone url

操作版本库

# 再本地版本库中创建一个README.md文件
touch README.md
# 添加该文件到本地仓库
git add README.md
# 提交到版本库,每次提交都需要加上提交描述
git commit -m '描述'
# 提交到本地版本库后同步到远程仓库
git push

分支管理

# 从当前分支创建新分支并切换到该分支(-b 表示切换到该分支)
git checkout -b dev || git switch -c dev
# 查看当前分支
git branch
# 将本地新分支推送到远程分支(远程分支名不一定要相同,但是一般保持一致)
git push -u origin branchName
# 将dev分支合并到master
git switch master
git merge dev || git rebase dev
# 删除本地分支
git branch -d branchName
# 删除远程分支
git branch -r -d origin/branchName
git push origin :branchName

git小技巧

# 通过命令编辑别名
git config --global alias.co checkout
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.br branch
git config --global alias.type 'cat-file -t'
git config --global alias.dump 'cat-file -p'
git config --global alias.stage 'add .'
git config --global alias.s 'switch'
git config --global alias.sc 'switch -c'
git config --global alias.hist "log --pretty=format:'%h %ad | %s%d [%an]' --graph --date=short"
git config --global alias.ls 'log --pretty=format:"%h %ad | %C(yellow)%h%Cred%d\ %Creset%s%Cblue\ [%cn]" --decorate'
git config --global alias.ll 'log --pretty=format:"%h %ad | %C(yellow)%h%Cred%d\ %Creset%s%Cblue\ [%cn]" --decorate --numstat'
git config --global alias.lg "log --color --graph --pretty=format:'%h %ad | %Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
git config --global color.ui auto
git config --global pager.branch false
git config --global --replace—=all core.pager cat
# 设置对大小写敏感
git config --global core.ignorecase false
git config --global color.status auto
git config --global color.diff auto
git config --global color.branch auto
git config --global color.interactive atuo
# 上传、拉取免密码操作
git config --global credential.helper store