命令行创建Github仓库

背景

不知道大家有没有像我一样经常遇到这种情况,本地写了个项目,想提交到Github时总是需要先在网页上打开Github,新建一个仓库,然后再将本地代码push上去。当然用Github客户端或其他三方的客户端也可以完成这个任务,但还是觉得麻烦,所以在网上搜了一下,终于找到了用命令行直接创建Github仓库的方法,原文在此,但是发现还是有一些问题,所以重新整理一下。

原理

通过Github官方API来实现

准备工作

  • 在GIthub上创建一个token
    https://github.com/settings/tokens
    权限scopes我没仔细看……尽量都勾上吧,注意要把personal access token记录下来,只显示一遍!
  • 本地设置token及用户名
    打开控制台,输入以下命令:
git config --global github.user <username>
git config --global github.token <token>

username为你Github的用户名,token就是上一步创建的token,注意不需要输入尖括号
实际两行命令是将你的git配置项写入~/.gitconfig文件

  • 创建本地git仓库:
    在你需要push到Github上的工程根目录执行:
touch README.md
git init
git add README.md
git commit -m "first commit"
  • 创建控制台脚本
    打开~/.bash_profile文件并添加如下代码:
ghc() 
{
  invalid_credentials=0
  repo_name=$1
  dir_name=`basename $(pwd)`
 
  if [ "$repo_name" = "" ]; then
    echo "Repo name (hit enter to use '$dir_name')?"
    read repo_name
  fi
 
  if [ "$repo_name" = "" ]; then
    repo_name=$dir_name
  fi
 
  username=`git config github.user`
  if [ "$username" = "" ]; then
    echo "Could not find username, run 'git config --global github.user <username>'"
    invalid_credentials=1
  fi
 
  token=`git config github.token`
  if [ "$token" = "" ]; then
    echo "Could not find token, run 'git config --global github.token <token>'"
    invalid_credentials=1
  fi
  if [ "$invalid_credentials" = 1 ]; then
    echo "fix error and try again"
    return 1
  fi
  echo -n "Creating Github repository '$repo_name' ..."
  curl -u "$username:$token" https://api.github.com/user/repos -d '{"name":"'$repo_name'"}' /dev/null 2>&1
  echo " done."
 
  echo -n "Pushing local code to remote ..."
  git remote add origin git@github.com:$username/$repo_name.git # > /dev/null 2>&1
  git push -u origin master  #> /dev/null 2>&1
  echo " done."
}

原文中缺少了invalid_credentials=0这行,导致如果在没有设置好tokenusername时执行了脚本, 则invalid_credentials不会被重置一直为1

将写好的脚本保存后再执行source ~/.bash_profile

  • 执行脚本
    在你的工程目录中执行ghc [repo name]默认仓库名为当前目录名,也可以手动输入

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。