git常用命令行和问题

126 阅读3分钟

命令行

初始化项目

git init  //生成.git文件(暂存区)

工作区 => 暂存区

git add 文件名 //提交单个文件
git add *  //提交所有文件
git commit -m "这次提交的描述" //提交操作

查看当前工作区状态

git status 

从暂存区恢复到工作区

git checkout 文件名

查看工作区和暂存区的区别

  • 哪些代码修改了
git diff

查看提交的历史版本

git log
git log --oneline --graph

恢复指定版本到文件

git reset --hard 版本号

第一次代码提交(暂存区=>远程仓库)

echo "# nextjs-users-manage" >> README.md // 创建readme.md文件
git init
git add *
git commit -m "first commit"
git branch -m main // 修改分支名为main
git remote add origin https://github.com(远程仓库地址) //第一次提交
git push -u origin master(分支) //提交失败使用下面强制推送并覆盖远程仓库
git push -f origin master // 强制提交

完整操作

git add *
git commit -m "操作描述"
git status //查看提交状态
git push //提交到远程仓库

从远程仓库克隆项目到本地

git clone 仓库地址

从远程仓库更新代码到本地

git pull

切换分支

git checkout 分支名

合并分支

git merge dev

给当前的commit创建新的标签

git tag <tag_name>

分支总结

git branch //查看所有分支
git branch -vv //查看本地分支和远程是否关联
git branch -r //查看远程分支
git branch -a //查看所有分支
git remote -v //查看仓库信息
git remote show origin //远程仓库和本地分支关联情况
git fetch //同步分支
git fetch --prune //同步并修剪分支
git branch <name> //创建新的分支
git checkout <name> //切换分支
git checkout -b <name> //创建并切换至新的分支
git merge <name> //将name分支合并至当前分支
git log --online --graph //查看具体log信息
git branch -d <name> //删除分支
git tag <tag_name> //为当前commit创建新的标签
git tag -d <tag_name> //删除标签

额外命令

tree .git

本地仓库和远程仓库关联

git remote add origin <你的远程仓库地址>
git push -u origin master

撤销git add 操作

git add   //添加了一些不想提交的文件
git reset //恢复之前的状态

从远程仓库下拉到本地,忽略覆盖更改过本地公共配置文件

git stash  //把公共配置隐藏起来
git pull //拉代码
git stash pop //把隐藏的取出来

多个分支代码拉取与推送

// dev 和 dev_yu 分支

// 先保持个人分支更新到最新代码
/* current branch: dev_yu */
git add *
git commit -m "操作描述"
git push origin dev_yu //提交到远程仓库个人分支dev_yu

git stash  //把修改的公共配置隐藏起来
git pull origin dev //同步远程dev分支to本地dev_yu分支

git add *
git commit -m "merge dev to dev_yu"
git push origin dev_yu //同步远程dev分支to远程仓库dev_yu分支

git checkout dev
/* current branch: dev */
git pull origin dev_yu //同步远程dev_yu分支to本地dev分支
git push origin dev //同步本地dev_yu分支to远程仓库dev分支

git checkout dev_yu

git stash pop // 把隐藏修改的公共配置的取出来

常见问题

  • 问题1: 'Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch'
press "i" (i for insert) // 进入编辑模式

write your merge message // 进行编辑

press "esc" (escape) // 退出编辑模式

write ":wq" (write & quit) // 退出

then press enter