I created a new local Git repository:
~$ mkdir projectname
~$ cd projectname
~$ git init
~$ touch file1
~$ git add file1
~$ git commit -m 'first commit'
Is there any git command to create a new remote repo and push my commit to GitHub from here? I know it's no big deal to just fire up a browser and head over to Create a New Repository, but if there is a way to achieve this from the CLI I would be happy.
I read a vast amount of articles but none that I found mention how to create a remote repo from the CLI using git commands. Tim Lucas's nice article Setting up a new remote git repository is the closest I found, but GitHub does not provide shell access.
This question is related to
git
github
ssh
command-line-interface
github-cli
Finally, it happened GitHub has officially announced their new CLI for all the core features.
check here: https://cli.github.com/
To install via HomeBrew: brew install gh
for other Ways : https://github.com/cli/cli#installation
then
gh repo create
Other available features.
$ gh --help
Work seamlessly with GitHub from the command line.
USAGE
gh <command> <subcommand> [flags]
CORE COMMANDS
gist: Create gists
issue: Manage issues
pr: Manage pull requests
release: Manage GitHub releases
repo: Create, clone, fork, and view repositories
ADDITIONAL COMMANDS
alias: Create command shortcuts
api: Make an authenticated GitHub API request
auth: Login, logout, and refresh your authentication
completion: Generate shell completion scripts
config: Manage configuration for gh
help: Help about any command
FLAGS
--help Show help for command
--version Show gh version
EXAMPLES
$ gh issue create
$ gh repo clone cli/cli
$ gh pr checkout 321
ENVIRONMENT VARIABLES
See 'gh help environment' for the list of supported environment variables.
LEARN MORE
Use 'gh <command> <subcommand> --help' for more information about a command.
Read the manual at https://cli.github.com/manual
FEEDBACK
Open an issue using 'gh issue create -R cli/cli'
So now you can create repo from your terminal.
For directions on creating a token, go here This is the command you will type (as of the date of this answer. (replace all CAPS keywords):
curl -u 'YOUR_USERNAME' -d '{"scopes":["repo"],"note":"YOUR_NOTE"}' https://api.github.com/authorizations
Once you enter your password you will see the following which contains your token.
{
"app": {
"name": "YOUR_NOTE (API)",
"url": "http://developer.github.com/v3/oauth/#oauth-authorizations-api"
},
"note_url": null,
"note": "YOUR_NOTE",
"scopes": [
"repo"
],
"created_at": "2012-10-04T14:17:20Z",
"token": "xxxxx",
"updated_at": "2012-10-04T14:17:20Z",
"id": xxxxx,
"url": "https://api.github.com/authorizations/697577"
}
You can revoke your token anytime by going here
create a new repository on the command line
echo "# <RepositoryName>" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/**<gituserID>/<RepositoryName>**.git
git push -u origin master
push an existing repository from the command line
git remote add origin https://github.com/**<gituserID>/<RepositoryName>**.git
git push -u origin master
here is my initial git commands (possibly, this action takes place in C:/Documents and Settings/your_username/
):
mkdir ~/Hello-World
# Creates a directory for your project called "Hello-World" in your user directory
cd ~/Hello-World
# Changes the current working directory to your newly created directory
touch blabla.html
# create a file, named blabla.html
git init
# Sets up the necessary Git files
git add blabla.html
# Stages your blabla.html file, adding it to the list of files to be committed
git commit -m 'first committttt'
# Commits your files, adding the message
git remote add origin https://github.com/username/Hello-World.git
# Creates a remote named "origin" pointing at your GitHub repository
git push -u origin master
# Sends your commits in the "master" branch to GitHub
Nope, you have to open a browser atleast once to create your username
on GitHub, once created, you can leverage GitHub API to create repositories from command line, following below command:
curl -u 'github-username' https://api.github.com/user/repos -d '{"name":"repo-name"}'
For example:
curl -u 'arpitaggarwal' https://api.github.com/user/repos -d '{"name":"command-line-repo"}'
Both the accepted answer and the most-voted answer so far are now outdated. Password authentication is deprecated and it will be removed on November 13, 2020 at 16:00 UTC.
The way to use GitHub API now is via personal access tokens.
You need to (replace ALL CAPS keywords):
curl -H 'Authorization: token MY_ACCESS_TOKEN' https://api.github.com/user/repos -d '{"name":"REPO"}'
or, to make it private from the start:
curl -H 'Authorization: token MY_ACCESS_TOKEN' https://api.github.com/user/repos -d '{"name":"REPO", "private":"true"}'
git remote add origin [email protected]:USER/REPO.git
git push origin master
This has the disadvantage that you have to type the token each time, and that it appears in your bash history.
To avoid this, you can
HEADER_FILE
)Authorization: token MY_ACCESS_TOKEN
curl -H @HEADER_FILE https://api.github.com/user/repos -d '{"name":"REPO"}' # public repo
curl -H @HEADER_FILE https://api.github.com/user/repos -d '{"name":"REPO", "private":"true"}' # private repo
chmod 400 HEADER_FILE
sudo chown root:root HEADER_FILE
sudo curl -H @HEADER_FILE https://api.github.com/user/repos -d '{"name":"REPO"}' # public repo
sudo curl -H @HEADER_FILE https://api.github.com/user/repos -d '{"name":"REPO", "private":"true"}' # private repo
You can create a GitHub repo via the command line using the GitHub API. Check out the repository API. If you scroll down about a third of the way, you'll see a section entitled "Create" that explains how to create a repo via the API (right above that is a section that explains how to fork a repo with the API, too). Obviously you can't use git
to do this, but you can do it via the command line with a tool like curl
.
Outside of the API, there's no way to create a repo on GitHub via the command line. As you noted, GitHub doesn't allow shell access, etc., so aside from the GitHub API, the only way to create a repo is through GitHub's web interface.
It is cumbersome to type the complete code every time a repository is to be created
curl -u 'USER' https://api.github.com/user/repos -d '{"name":"REPO"}'
git remote add origin [email protected]:USER/REPO.git
git push origin master
An easier approach is:
githubscript.sh
githubscript.sh
file
#!bin/bash
curl -u 'YOUR_GITHUB_USER_NAME' https://api.github.com/user/repos -d "{\"name\":\"$1\"}";
git init;
git remote add origin [email protected]:YOUR_GITHUB_USER_NAME/$1.git;
N.B. Here $1
is the repository name
that is passed as an argument
when invoking the script
Change YOUR_GITHUB_USER_NAME
before saving the script.
Set required permissions to the script
file
chmod 755 githubscript.sh
Include the scripts directory in the environment configuration file.
nano ~/.profile;
export PATH="$PATH:$HOME/Desktop/my_scripts"
Also set an alias to run the githubscript.sh file.
nano ~/.bashrc;
alias githubrepo="bash githubscript.sh"
Now reload the .bashrc
and .profile
files in the terminal.
source ~/.bashrc ~/.profile;
Now to create a new repository i.e. demo
:
githubrepo demo;
Update 20200714
Github has a new official CLI.
...gh is a new project that helps us explore what an official GitHub CLI tool can look like with a fundamentally different design. While both tools bring GitHub to the terminal, hub behaves as a proxy to git, and gh is a standalone tool.
The core difference from hub is that this does not wrap over existing git commands. So, you can not alias git to gh like you can with hub.
We didn't add it to hub because we decided to design GitHub CLI differently than being a git wrapper, i.e. as its own command. It turns out, maintaining an executable that's a proxy to git is hard to maintain, and also we didn't want to be limited by having to always keep git compatibility. We didn't want to build GitHub CLI on a paradigm that is brittle from the start.
-- mislav (Maintainer of hub)
Original answer
What you need is hub. Hub is a command-line wrapper for git. It has been made to integrate with native git using alias. It tries to provide github actions into git including creating new repository.
? create a repo for a new project
$ git init
$ git add . && git commit -m "It begins."
$ git create -d "My new thing"
? (creates a new project on GitHub with the name of current directory)
$ git push origin master
This can be done with three commands:
curl -u 'nyeates' https://api.github.com/user/repos -d '{"name":"projectname","description":"This project is a test"}'
git remote add origin [email protected]:nyeates/projectname.git
git push origin master
(updated for v3 Github API)
curl -u 'nyeates' https://api.github.com/user/repos -d '{"name":"projectname","description":"This project is a test"}'
git remote add origin [email protected]:nyeates/projectname.git
git push origin master
For Rubyists:
gem install githubrepo
githubrepo create *reponame*
enter username and pw as prompted
git remote add origin *ctrl v*
git push origin master
Source: Elikem Adadevoh
I've created a Git alias to do this, based on Bennedich's answer. Add the following to your ~/.gitconfig
:
[github]
user = "your_github_username"
[alias]
; Creates a new Github repo under the account specified by github.user.
; The remote repo name is taken from the local repo's directory name.
; Note: Referring to the current directory works because Git executes "!" shell commands in the repo root directory.
hub-new-repo = "!python3 -c 'from subprocess import *; import os; from os.path import *; user = check_output([\"git\", \"config\", \"--get\", \"github.user\"]).decode(\"utf8\").strip(); repo = splitext(basename(os.getcwd()))[0]; check_call([\"curl\", \"-u\", user, \"https://api.github.com/user/repos\", \"-d\", \"{{\\\"name\\\": \\\"{0}\\\"}}\".format(repo), \"--fail\"]); check_call([\"git\", \"remote\", \"add\", \"origin\", \"[email protected]:{0}/{1}.git\".format(user, repo)]); check_call([\"git\", \"push\", \"origin\", \"master\"])'"
To use it, run
$ git hub-new-repo
from anywhere inside the local repository, and enter your Github password when prompted.
For rep reasons, I can't add this as a comment (where it would better go with bennedich's answer), but for Windows command line, here is the correct syntax:
curl -u YOUR_USERNAME https://api.github.com/user/repos -d "{\"name\":\"YOUR_REPO_NAME\"}"
It's the same basic form, but you have to use double quotes (") instead of single, and escape the double quotes sent in the POST parameters (after the -d flag) with backslashes. I also removed the single quotes around my username, but if your username had a space (possible?) it would probably need double quotes.
There is an official github gem which, I think, does this. I'll try to add more information as I learn, but I'm only just now discovering this gem, so I don't know much yet.
UPDATE: After setting my API key, I am able to create a new repo on github via the create
command, however I am not able to use the create-from-local
command, which is supposed to take the current local repo and make a corresponding remote out on github.
$ gh create-from-local
=> error creating repository
If anyone has some insight on this, I'd love to know what I'm doing wrong. There's already an issue filed.
UPDATE: I did eventually get this to work. I'm not exactly sure how to re-produce the issue, but I just started from scratch (deleted the .git folder)
git init
git add .emacs
git commit -a -m "adding emacs"
Now this line will create the remote repo and even push to it, but unfortunately I don't think I can specify the name of the repo I'd like. I wanted it to be called "dotfiles" out on github, but the gh gem just used the name of the current folder, which was "jason" since I was in my home folder. (I added a ticket asking for the desired behavior)
gh create-from-local
This command, on the other hand, does accept an argument to specify the name of the remote repo, but it's intended for starting a new project from scratch, i.e. after you call this command, you get a new remote repo that's tracking a local repo in a newly-created subfolder relative to your current position, both with the name specified as the argument.
gh create dotfiles
Based on the other answer by @Mechanical Snail, except without the use of python, which I found to be wildly overkill. Add this to your ~/.gitconfig
:
[github]
user = "your-name-here"
[alias]
hub-new-repo = "!REPO=$(basename $PWD) GHUSER=$(git config --get github.user); curl -u $GHUSER https://api.github.com/user/repos -d {\\\"name\\\":\\\"$REPO\\\"} --fail; git remote add origin [email protected]:$GHUSER/$REPO.git; git push origin master"
CLI commands for github API v3 (replace all CAPS keywords):
curl -u 'USER' https://api.github.com/user/repos -d '{"name":"REPO"}'
# Remember replace USER with your username and REPO with your repository/application name!
git remote add origin [email protected]:USER/REPO.git
git push origin master
For users with two-factor authentication, you can use bennedich's solution, but you just need to add the X-Github-OTP header for the first command. Replace CODE with the code that you get from the two-factor authentication provider. Replace USER and REPO with the username and name of the repository, as you would in his solution.
curl -u 'USER' -H "X-GitHub-OTP: CODE" -d '{"name":"REPO"}' https://api.github.com/user/repos
git remote add origin [email protected]:USER/REPO.git
git push origin master
For all the Python 2.7.* users. There is a Python wrapper around the Github API that is currently on Version 3, called GitPython. Simply install using easy_install PyGithub
or pip install PyGithub
.
from github import Github
g = Github(your-email-addr, your-passwd)
repo = g.get_user().user.create_repo("your-new-repos-name")
# Make use of Repository object (repo)
The Repository
object docs are here.
Disclamier: I'm the author of the open source project
This functionality is supported by: https://github.com/chrissound/Human-Friendly-Commands essentially it is this script:
#!/usr/bin/env bash
# Create a repo named by the current directory
# Accepts 1 STRING parameter for the repo description
# Depends on bin: jq
# Depends on env: GITHUB_USER, GITHUB_API_TOKEN
github_createRepo() {
projName="$(basename "$PWD")"
json=$(jq -n \
--arg name "$projName" \
--arg description "$1" \
'{"name":$name, "description":$description}')
curl -u "$GITHUB_USER":"$GITHUB_API_TOKEN" https://api.github.com/user/repos -d "$json"
git init
git remote add origin [email protected]:"$GITHUB_USER"/"$projName".git
git push origin master
};
I wrote a nifty script for this called Gitter using the REST APIs for GitHub and BitBucket:
https://github.com/dderiso/gitter
BitBucket:
gitter -c -r b -l javascript -n node_app
GitHub:
gitter -c -r g -l javascript -n node_app
-c
= create new repo-r
= repo provider (g = GitHub, b = BitBucket)-n
= name the repo-l
= (optional) set the language of the app in the repoFound this solution which I liked: https://medium.com/@jakehasler/how-to-create-a-remote-git-repo-from-the-command-line-2d6857f49564
You first need to create a Github Personal Access Token
Open up your ~/.bash_profile or ~/.bashrc in your favorite text editor. Add the following line near the top of your file, where the rest of the export ‘ed variables are:
export GITHUB_API_TOKEN=<your-token-here>
Somewhere below, by your other bash functions, you can paste something similar to the following:
function new-git() {
curl -X POST https://api.github.com/user/repos -u <your-username>:$GITHUB_API_TOKEN -d '{"name":"'$1'"}'
}
Now, whenever you’re creating a new project, you can run the command $ new-git awesome-repo
to create a new public remote repository on your Github user account.
Simple steps (using git
+ hub
=> GitHub):
Go to your repo or create empty one: mkdir foo && cd foo && git init
.
Run: hub create
, it'll ask you about GitHub credentials for the first time.
Usage: hub create [-p] [-d DESCRIPTION] [-h HOMEPAGE] [NAME]
Example: hub create -d Description -h example.com org_name/foo_repo
Hub will prompt for GitHub username & password the first time it needs to access the API and exchange it for an
OAuth
token, which it saves in~/.config/hub
.To explicitly name the new repository, pass in
NAME
, optionally inORGANIZATION/NAME
form to create under an organization you're a member of.With
-p
, create a private repository, and with-d
and-h
set the repository's description and homepageURL
, respectively.To avoid being prompted, use
GITHUB_USER
andGITHUB_PASSWORD
environment variables.
Then commit and push as usual or check hub commit
/hub push
.
For more help, run: hub help
.
See also: Importing a Git repository using the command line at GitHub.
Source: Stackoverflow.com