三种直接在命令行创建GitHub仓库的形式

在使用github时总不想使用图形界面去创建远程仓库,如果有一种方法可以直接在terminal上创建那就好,看到此文使用github的API觉得非常好,翻译过来,希望对各位有些帮助。


这里主要介绍三种直接从命令行创建仓库的形式,其实是一种方法。第一种形式,一条命令;第二种把命令存成bash语句;第三种是第二种的简化版。

 

零、准备工作

0.进入一个目录,这个目录是本地仓库的目录;

1.在本地建立仓库

		git init && git add . && git commit -m 'some information'

2.新建一个API token

打开此链接,generate new token,写入description,选择scopes(设置此token持有者的权限)。记住personal access token(也就是那一串字符和数字)!这一串东西只出现一次,下次查看不到。

 

一、命令行形式

这是最直接的一种形式,直接把参数写到命令行搞定:

curl -u "$username:$token" https://api.github.com/user/repos -d '{"name":"'$repo_name'"}'

注:这里需要把$username$token分别换成实际的用户名和刚才记住的personal access token,把$repo_name换成任何想要的repo name

 

二、bash 形式

我们可以把命令行写成bash脚本,下次只要执行里面的简单命令就可以执行以上整条命令。

0.把usernametoken写入(apend或者修改)~/.gitconfig,形式如下:

[github]
	user = your user name 
	token = the token you get

1.把如下bash code写入(append~/.bash_profile文件

github-create() {
  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
    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 [email protected]:$username/$repo_name.git > /dev/null 2>&1
  git push -u origin master > /dev/null 2>&1
  echo " done."
}

2.重新打开或新启动一个Termina,或者也可以在当前Terminal下运行如下命令

	Source  ~/.bash_profile

3.然后就可以用如下命令创建远程仓库了

<span style="white-space:pre">	</span>github-create [repo name]

如果你不想用默认repo名(也就是当前目录名)创建repo可以重新输入另一个名字,否则直接按回车执行。

 

这是一种比较健壮的形式,其usernametoken,repo name 都有很大的自由度,接下来这种非常简单,但在不同情况下有时需要被直接修改。


三、bash形式--简化版

0.把如下bash code写入(append~/.bash_profile文件。第十行按照形式一处理一下。

simple-create() {
  if [ $1 ]
  then
    repo_name=$1
  else
    echo "Repo name?"
    read repo_name
  fi
 
  curl -u '$username:$token' https://api.github.com/user/repos -d '{"name":"'$repo_name'"}'
  git remote add origin [email protected]:efatsi/$repo_name.git
  git push -u origin master
}



1.同第二种形式的步骤2

2.执行命令

		simple-create [repo name]

四、备注

本文翻译自此文,全部命令本人已经验证可行,如有问题您既可以在这儿提出也可以直接和原作者交流。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章