1
2
お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

ローカルリポジトリを作成してgithubにリモートリポジトリとしてコマンドで追加する方法

Last updated at Posted at 2024-06-25

本記事ではローカルリポジトリを作成してgithubにリモートリポジトリとして追加する方法について記載する.

以下のgitの知識は知っていることを前提とする.gitの基礎のついてわからない方は一読することをお勧めする.

githubCLIのインストール

brew install gh 

githubにログインする

gh auth login 

GitHub.comGitHub Enterprise Serverかを選択する.個人利用ならGitHub.comを選択すれば良い,

? What account do you want to log into?  [Use arrows to move, type to filter]
> GitHub.com
  GitHub Enterprise Server

HTTPSSSHを選択する

? What is your preferred protocol for Git operations on this host?  [Use arrows to move, type to filter]
> HTTPS
  SSH

Yと入力してEnter

? Authenticate Git with your GitHub credentials? (Y/n)

Login with a web browserで良いと思う.ブラウザでgithubへログインすることになる.

? How would you like to authenticate GitHub CLI?  [Use arrows to move, type to filter]
> Login with a web browser
  Paste an authentication token

その後,以下のように表示されるのでone-time codeを控えておく.

0000-0000は英数字で表示され,ユーザ,タイミングによって異なる値である.

! First copy your one-time code: 0000-0000
Press Enter to open github.com in your browser...

web上でone-time codeを入力し,githubにログインすると以下のように表示される.

✓ Authentication complete.
- gh config set -h github.com git_protocol https
✓ Configured git protocol
✓ Logged in as <githubアカウント名>

リモートリポジトリの作成

このコマンドでリモートに新しくリポジトリを作成する.

プライベートリポジトリなら
gh repo create <リモートリポジトリ名> --private
パブリックリポジトリなら
gh repo create <リモートリポジトリ名> --public

自分のGithubアカウントに紐付いた組織アカウントにリモートリポジトリを作成するなら

プライベートリポジトリなら
gh repo create <組織アカウント名>/<リモートリポジトリ名> --private

この時点でgithubにアクセスすると自分のリポジトリに作成したものが反映されているはずである.

ローカルリポジトリの作成

まずディレクトリを作成する

mkdir yourdirectoryname
cd yourdirectoryname

以下のコマンドで.gitファイルを作成する.これでローカルリポジトリが作成できる

git init

ローカリリポジトリとリモートリポジトリの関連付け

ローカルリポジトリがGitHubのリモートリポジトリに関連付けられる.

git remote add origin https://github.com/<アカウント名>/<リモートリポジトリ名>.git

https://github.com/<アカウント名>/<リモートリポジトリ名>.gitは作成したリモートリポジトリのURLなのでgithubからコピペでも良い

ローカルリポジトリでコミットする

新しく変更差分を作る(ファイルを追加,編集,削除する)
その後,git addをする.

git add <ファイル名>

git add .でカレントディレクトリすべてのファイルを,git add *でリポジトリ内すべてのファイルをステージングエリアにaddする.

git commit -m "コミットメッセージ"

リモートリポジトリにプッシュする

git push origin main

これでgithubにアクセスすればリモートにプッシュした内容が反映されている.

github.com上のリモートリポジトリにコマンドでアクセスする方法

githubCLIにログインしている場合

gh browse

githubCLIにログインしていない場合

以下のコマンドを実行するとローカルリポジトリに結びついたリモートリポジトリにアクセスできる.
Macでは

open $(git remote get-url origin)

Windowsでは(PowerShellで)

start (git remote get-url origin)
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2