命令行创建Github仓库

作者: xinayida | 来源:发表于2017-08-12 00:48 被阅读30次

背景

不知道大家有没有像我一样经常遇到这种情况,本地写了个项目,想提交到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" = 0 ]; 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]默认仓库名为当前目录名,也可以手动输入

参考

相关文章

  • 命令行创建Github仓库

    背景 不知道大家有没有像我一样经常遇到这种情况,本地写了个项目,想提交到Github时总是需要先在网页上打开Git...

  • Electron开发实战之02-github

    源码 j、源码 j-step-c2、相关视频 在 github上创建仓库 j-step创建仓库 通过你的命令行终端...

  • git笔记(一)

    创建GitHub仓库 默认即可,效果如下图 命令行创建本机仓库 提交新的更改 重置上一次提交 抓取远程代码到本地 ...

  • 发布自己的cocoapods插件

    创建本地Git仓库,并提交代码 创建GitHub远端仓库,提交本地代码至GitHub仓库GitHub创建仓库.pn...

  • Git 最简单使用帮助

    初始化并同步仓库 先在GitHub创建好仓库 在本地,打开Git命令行,输入git init初始化本地仓库 git...

  • 创建Git项目

    从命令行创建一个仓库 从命令行推送已经创建的仓库

  • 从零创建一个Git项目

    从零创建一个Git项目 从命令行创建一个仓库 从命令行推送已经创建的仓库

  • 命令行上传文件到github

    1、先登录github创建仓库 2、打开命令行cd到你要上传的文件 3、添加新的文件

  • 搭建Github Pages个人博客网站

    目录 引言关于博客关于Github 创建Github账号 创建仓库填充仓库配置Github Pages功能 博客的...

  • 2018-07-16 git学习-远程库

    一、远程仓库 1、登录GitHub,创建一个新的仓库 2、创建本地仓库和github仓库关联 git remot...

网友评论

    本文标题:命令行创建Github仓库

    本文链接:https://www.haomeiwen.com/subject/qhqdrxtx.html