Как создать репозиторий на github через консоль
Перейти к содержимому

Как создать репозиторий на github через консоль

  • автор:

Настройка Git

At the heart of GitHub is an open-source version control system (VCS) called Git. Git is responsible for everything GitHub-related that happens locally on your computer.

С помощью Git

Для работы с Git в командной строке необходимо скачать, установить и настроить Git на компьютере. Также вы можете установить GitHub CLI для работы с GitHub из командной строки. Дополнительные сведения см. в разделе «AUTOTITLE».

Если вы хотите работать с Git локально, но не хотите использовать командную строку, вы можете скачать и установить клиент GitHub Desktop . Дополнительные сведения см. в разделе «AUTOTITLE».

Если вам не требуется работать с файлами локально, множество связанных с Git действий можно выполнять с помощью GitHub непосредственно в браузере:

  • Краткое руководство по репозиториям
  • Вилка репозитория
  • Управление файлами

Настройка Git

  1. Установите на устройство с Chrome OS эмулятор терминала, например Termux, из Google Play Маркет.
  2. Установите Git из установленного эмулятора терминала. Например, в Termux введите apt install git и затем y при появлении запроса.

Проверка подлинности с помощью GitHub из Git

При подключении к репозиторию GitHub из Git необходимо пройти проверку подлинности в GitHub с использованием протокола HTTPS или SSH.

Примечание. Для проверки подлинности в GitHub можно использовать GitHub CLI для HTTP или SSH. Дополнительные сведения см. в разделе gh auth login .

Подключение по протоколу HTTPS (рекомендуется)

При клонировании по протоколу HTTPS вы можете кэшировать учетные данные GitHub в Git с помощью вспомогательного приложения для управления учетными данными. Дополнительные сведения см. в разделе «[AUTOTITLE» и «Сведения об удаленных репозиториях](/get-started/getting-started-with-git/caching-your-github-credentials-in-git)».

Подключение по протоколу SSH

При клонировании по протоколу SSH необходимо создать ключи SSH на каждом компьютере, который будет использоваться для отправки или извлечения данных из GitHub. Дополнительные сведения см. в разделе «[AUTOTITLE» и «Сведения об удаленных репозиториях](/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent)».

Следующие шаги

Настройка Git и GitHub завершена. Теперь вы можете создать репозиторий, в котором будут размещаться ваши проекты. В репозитории вы можете хранить резервные копии своего кода и обеспечить возможность доступа к нему пользователям по всему миру.

  • Создание репозитория для проекта позволяет хранить код на GitHub. Таким образом вы получаете резервную копию результатов работы, которую можно предоставить другим разработчикам. Дополнительные сведения см. в разделе «Краткое руководство по репозиториям»..
  • Создание вилки репозитория позволит вносить изменения в другой репозиторий, не затрагивая исходный. Дополнительные сведения см. в разделе «AUTOTITLE».
  • Каждый репозиторий на GitHub принадлежит пользователю или организации. Вы можете взаимодействовать с людьми, репозиториями и организациями, подписавшись на них на GitHub. Дополнительные сведения см. в разделе «AUTOTITLE».
  • У GitHub большое сообщество поддержки, где можно обратиться за помощью и поговорить с людьми со всего мира. Присоединиться к беседе можно в GitHub Community.

Запуск GitHub Desktop из командной строки

Снимок экрана: строка меню на Компьютере Mac. В раскрывающемся меню

  1. В строке меню выберите меню GitHub Desktop и нажмите кнопку Установить программу командной строки.
github /PATH/TO/REPO 

Вы также можете изменить путь к репозиторию, а затем ввести github . , чтобы открыть этот репозиторий.

$ cd /PATH/TO/REPO [repo]$ github . 
  1. Откройте командную строку.
  2. Чтобы запустить GitHub Desktop для последнего открытого репозитория, введите github . Чтобы запустить GitHub Desktop для определенного репозитория, введите github и затем путь к репозиторию.
C:\Users\octocat> github PATH\TO\REPO 

Вы также можете изменить путь к репозиторию, а затем ввести github . , чтобы открыть этот репозиторий.

C:\Users\octocat> cd REPO\MY-REPO C:\Users\octocat\repo\myrepo> github . 

Добавление локально размещенного кода в GitHub

If your code is stored locally on your computer and is tracked by Git or not tracked by any version control system (VCS), you can import the code to GitHub using GitHub CLI or Git commands.

Platform navigation

About adding existing source code to GitHub

If you have source code stored locally on your computer that is tracked by Git or not tracked by any version control system (VCS), you can add the code to GitHub by typing commands in a terminal. You can do this by typing Git commands directly, or by using GitHub CLI.

GitHub CLI is an open source tool for using GitHub from your computer’s command line. GitHub CLI can simplify the process of adding an existing project to GitHub using the command line. To learn more about GitHub CLI, see «About GitHub CLI.»

Note: If you’re most comfortable with a point-and-click user interface, consider adding your project with GitHub Desktop instead. For more information, see «Adding a repository from your local computer to GitHub Desktop.»

If your source code is tracked by a different VCS, such as Mercurial, Subversion, or Team Foundation Version Control, you must convert the repository to Git before you can add the project to GitHub.

  • «Importing a Subversion repository»
  • «Importing a Mercurial repository»
  • «Importing a Team Foundation Version Control repository»

Warning: Never git add , commit , or push sensitive information to a remote repository. Sensitive information can include, but is not limited to:

  • Passwords
  • SSH keys
  • AWS access keys
  • API keys
  • Credit card numbers
  • PIN numbers

Initializing a Git repository

If your locally-hosted code isn’t tracked by any VCS, the first step is to initialize a Git repository. If your project is already tracked by Git, skip to «Importing a Git repository with the command line.»

  1. Open Terminal Terminal Git Bash .
  2. Navigate to the root directory of your project.
  3. Initialize the local directory as a Git repository. By default, the initial branch is called main . If you’re using Git 2.28.0 or a later version, you can set the name of the default branch using -b .

git init -b main 

If you’re using Git 2.27.1 or an earlier version, you can set the name of the default branch using git symbolic-ref .

git init && git symbolic-ref HEAD refs/heads/main 
$ git add . # Adds the files in the local repository and stages them for commit. To unstage a file, use 'git reset HEAD YOUR-FILE'. 
$ git commit -m "First commit" # Commits the tracked changes and prepares them to be pushed to a remote repository. To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again. 

Importing a Git repository with the command line

After you’ve initialized a Git repository, you can push the repository to GitHub, using either GitHub CLI or Git.

  • «Adding a local repository to GitHub with GitHub CLI»
  • «Adding a local repository to GitHub using Git»

Adding a local repository to GitHub with GitHub CLI

  1. To create a repository for your project on GitHub, use the gh repo create subcommand. When prompted, select Push an existing local repository to GitHub and enter the desired name for your repository. If you want your project to belong to an organization instead of your user account, specify the organization name and project name with organization-name/project-name .
  2. Follow the interactive prompts. To add the remote and push the repository, confirm yes when asked to add the remote and push the commits to the current branch.
  3. Alternatively, to skip all the prompts, supply the path to the repository with the —source flag and pass a visibility flag ( —public , —private , or —internal ). For example, gh repo create —source=. —public . Specify a remote with the —remote flag. To push your commits, pass the —push flag. For more information about possible arguments, see the GitHub CLI manual.

Adding a local repository to GitHub using Git

Before you can add your local repository to GitHub using Git, you must authenticate to GitHub on the command line. For more information, see «About authentication to GitHub.»

  1. Create a new repository on GitHub.com. To avoid errors, do not initialize the new repository with README, license, or gitignore files. You can add these files after your project has been pushed to GitHub. For more information, see «Creating a new repository.»
  2. At the top of your repository on GitHub.com’s Quick Setup page, click

Screenshot of the

to copy the remote repository URL.

git remote add origin REMOTE-URL 
git remote -v 
git push -u origin main 
  1. Create a new repository on GitHub.com. To avoid errors, do not initialize the new repository with README, license, or gitignore files. You can add these files after your project has been pushed to GitHub. For more information, see «Creating a new repository.»
  2. At the top of your repository on GitHub.com’s Quick Setup page, click

Screenshot of the

to copy the remote repository URL.

git remote add origin REMOTE-URL 
git remote -v 
git push origin main 
  1. Create a new repository on GitHub.com. To avoid errors, do not initialize the new repository with README, license, or gitignore files. You can add these files after your project has been pushed to GitHub. For more information, see «Creating a new repository.»
  2. At the top of your repository on GitHub.com’s Quick Setup page, click

Screenshot of the

to copy the remote repository URL.

git remote add origin REMOTE-URL 
git remote -v 
git push origin main 

Further reading

  • «Adding a file to a repository»
  • «Troubleshooting the 2 GB push limit»

Можно ли создать репозиторий GitHub через консоль?

Например, я не хочу заходить в браузер и создавать через аккаунт GitHub публичный репозиторий, можно ли это сделать через терминал (консоль)?

  • Вопрос задан более трёх лет назад
  • 4848 просмотров

Комментировать
Решения вопроса 2

yvikt

it-шник самоучка

Так как среди ответов я не нашел что искал, вот что, как я понял, хотел узнать автор вопроса:
Не используя браузер создать на Github репозиторий используя только командную строку — так сказать удаленно.
Для того чтобы это было возможно в этот раз и в будущем, все же необходимо зайти на github и создать токен доступа к API гитхаба. Делается это по следующей инструкции https://docs.github.com/en/free-pro-team@latest/gi.
Токен используется в качестве пароля для команды curl использование которой для целей создания репозитоория описывается в виде примеров здесь https://coderoad.ru/2423777/Можно-ли-создать-удале.

Ниже привожу полный список команд начиная от создания папки с проектом и заканчивая его залитием на вновь созданный репозиторий:

mkdir test cd test git init echo "This repo was created remotely" >> README.md git add . git commit -m "first commit" git remote add origin git@github.com:USER/test.git curl -u 'USER:TOKEN' https://api.github.com/user/repos -d '' git push -u origin master

USER — ваш логин на гитхабе
TOKEN — токен типа 6ccfd64d55fc1ca1cc26ffe2b9351cc9 сгенерированый по инструкции

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *