在使用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.把username和token寫入(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可以重新輸入另一個名字,否則直接按回車執行。
這是一種比較健壯的形式,其username,token,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]
四、備註
本文翻譯自此文,全部命令本人已經驗證可行,如有問題您既可以在這兒提出也可以直接和原作者交流。