- Как пользоваться GitHub на компьютере с Linux
- Установка git
- Синтаксис
- Создание проекта на локальном компьютере
- Отправка данных на GitHub
- Создание репозитория
- Заливаем проект в репозиторий на GitHub
- Получение файлов с GitHub
- Клонирование проекта
- Возможные ошибки
- 1. При попытке отправить данные на GitHub, получаем ошибку:
- Git Guides
- Get started with git and GitHub
- Set up Git
- Help us make these docs great!
- Using github on linux
- Installing and using Git and GitHub on Ubuntu Linux
- Introduction:
- Installing Git on Ubuntu Linux
- Configuring Git:
- Describe —global flag
- Using Git:
- Git Repository
- Git Staging Area:
- Conclusion:
Как пользоваться GitHub на компьютере с Linux
GitHub — один из используемых сервисов размещения проектов для совместной разработки. Он поддерживает контроль версий, возможность отслеживания изменений кода, сравнение строк, а также он бесплатен.
В данной статье приведены примеры использования сервиса на компьютере под управлением операционных систем семейства Linux. Мы рассмотрим, как создать проект на локальном компьютере и залить его на сервис с помощью командной строки. Рассмотренные варианты использования git также можно применять на desktop системах, запустив окно терминала.
Установка git
Управление выполняется с помощью приложения git. Если его нет в системе, установку можно выполнить из репозитория.
Если используем CentOS / Red Hat:
yum install git-core
Если используем Ubuntu / Debian:
apt-get install git
Если мы хотим воспользоваться сервисом с компьютера Windows или Mac OS, необходимо скачать и установить desktop версию с официального сайта.
Синтаксис
Команды имеют следующий синтаксис:
* полный перечень опций, команд и аргументов можно получить командой man git.
Создание проекта на локальном компьютере
Прежде чем отправить проект на GitHub, создаем его на нашем компьютере. Для этого переходим в каталог с файлами проекта:
Инициализируем проект для git:
Мы получим ответ похожий на:
Initialized empty Git repository in /projects/.git/
Это означает, что репозиторий git создан.
Теперь добавим файлы в репозиторий:
* данной командой мы добавили папку и ее содержимое в репозиторий git.
Отправка данных на GitHub
Теперь можно отправить данные на сервис. Для этого у нас должна быть зарегистрированная учетная запись и создан репозиторий на GitHub.
Создание репозитория
Переходим на портал github.com и входим в систему или проходим несложную регистрацию:
Проходим процесс подтверждения, что мы не робот. Затем завершаем несколько шагов регистрации, нажимая Submit. В итоге мы получим письмо на адрес электронной почты, которую указали при регистрации. Необходимо будем подтвердить email, перейдя в письме по кнопке Verify email address.
Создаем репозиторий. Для этого кликаем по иконке профиля и переходим в раздел Your repositories:
И кликаем по кнопке New. В следующем окне даем название репозиторию и нажимаем Create repository:
Мы увидим страницу с путем к репозиторию:
Заливаем проект в репозиторий на GitHub
Добавляем комментарий к нашему проекту:
git commit -m «Очередное изменение проекта» -a
* где Очередное изменение проекта — произвольный комментарий; параметр -a указывает, что комментарий нужно применить ко всем измененным файлам.
Теперь подключаемся к созданному репозиторию:
git remote add origin https://github.com/dmosktest/project1.git
* где dmosktest — логин, который был указан при регистрации на github, а project1 — название, которое мы задали, когда создавали репозиторий.
* удалить удаленный репозиторий можно командой git remote rm origin.
Закидываем проект на GitHub:
git push origin master
* где master — ветка проекта (веток может быть несколько).
В нашем проекте на GitHub должны появиться файлы проекта:
Получение файлов с GitHub
Для загрузки на компьютер файлов, создаем каталог с проектом и переходим в него:
Проводим начальную настройку локального репозитория:
Подключаемся к удаленному репозиторию:
git remote add origin https://github.com/dmosktest/project1.git
Скачиваем проект командой:
git pull https://github.com/dmosktest/project1.git master
Клонирование проекта
Например, использую наш репозиторий:
git clone https://github.com/dmosktest/project1.git
* данная команда создаст в текущей папке каталог project1 и инициализирует его как локальный репозиторий git. Также загрузит файлы проекта.
Возможные ошибки
1. При попытке отправить данные на GitHub, получаем ошибку:
error: src refspec master does not match any.
error: failed to push some refs to ‘https://github.com/dmosktest/project1.git’
* где dmosktest/project1.git — путь к нашему репозиторию.
Причина: проект ни разу не был зафиксирован (закоммичен).
Решение: добавляем комментарий к нашему проекту:
Источник
Git Guides
How to install Git on any OS
Git can be installed on the most common operating systems like Windows, Mac, and Linux. In fact, Git comes installed by default on most Mac and Linux machines!
Checking for Git
To see if you already have Git installed, open up your terminal application.
- If you’re on a Mac, look for a command prompt application called «Terminal».
- If you’re on a Windows machine, open the windows command prompt or «Git Bash».
Once you’ve opened your terminal application, type git version . The output will either tell you which version of Git is installed, or it will alert you that git is an unknown command. If it’s an unknown command, read further and find out how to install Git.
Install Git Using GitHub Desktop
Installing GitHub Desktop will also install the latest version of Git if you don’t already have it. With GitHub Desktop, you get a command line version of Git with a robust GUI. Regardless of if you have Git installed or not, GitHub Desktop offers a simple collaboration tool for Git. You can learn more here.
Install Git on Windows
- Navigate to the latest Git for Windows installer and download the latest version.
- Once the installer has started, follow the instructions as provided in the Git Setup wizard screen until the installation is complete.
- Open the windows command prompt (or Git Bash if you selected not to use the standard Git Windows Command Prompt during the Git installation).
- Type git version to verify Git was installed.
Note: git-scm is a popular and recommended resource for downloading Git for Windows. The advantage of downloading Git from git-scm is that your download automatically starts with the latest version of Git included with the recommended command prompt, Git Bash . The download source is the same Git for Windows installer as referenced in the steps above.
Install Git on Mac
Most versions of MacOS will already have Git installed, and you can activate it through the terminal with git version . However, if you don’t have Git installed for whatever reason, you can install the latest version of Git using one of several popular methods as listed below:
Install Git From an Installer
- Navigate to the latest macOS Git Installer and download the latest version.
- Once the installer has started, follow the instructions as provided until the installation is complete.
- Open the command prompt «terminal» and type git version to verify Git was installed.
Note: git-scm is a popular and recommended resource for downloading Git on a Mac. The advantage of downloading Git from git-scm is that your download automatically starts with the latest version of Git. The download source is the same macOS Git Installer as referenced in the steps above.
Install Git from Homebrew
Homebrew is a popular package manager for macOS. If you already have Homwbrew installed, you can follow the below steps to install Git:
- Open up a terminal window and install Git using the following command: brew install git .
- Once the command output has completed, you can verify the installation by typing: git version .
Install Git on Linux
Fun fact: Git was originally developed to version the Linux operating system! So, it only makes sense that it is easy to configure to run on Linux.
You can install Git on Linux through the package management tool that comes with your distribution.
- Git packages are available using apt .
- It’s a good idea to make sure you’re running the latest version. To do so, Navigate to your command prompt shell and run the following command to make sure everything is up-to-date: sudo apt-get update .
- To install Git, run the following command: sudo apt-get install git-all .
- Once the command output has completed, you can verify the installation by typing: git version .
- Git packages are available using dnf .
- To install Git, navigate to your command prompt shell and run the following command: sudo dnf install git-all .
- Once the command output has completed, you can verify the installation by typing: git version .
Note: You can download the proper Git versions and read more about how to install on specific Linux systems, like installing Git on Ubuntu or Fedora, in git-scm’s documentation.
Other Methods of Installing Git
Looking to install Git via the source code? Learn more here.
Get started with git and GitHub
Review code, manage projects, and build software alongside 40 million developers.
Источник
Set up 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.
To use Git on the command line, you’ll need to download, install, and configure Git on your computer. You can also install GitHub CLI to use GitHub from the command line. For more information, see «About GitHub CLI.»
If you want to work with Git locally, but don’t want to use the command line, you can instead download and install the GitHub Desktop client. For more information, see «Installing and configuring GitHub Desktop.»
If you don’t need to work with files locally, GitHub lets you complete many Git-related actions directly in the browser, including:
Next steps: Authenticating with GitHub from Git
When you connect to a GitHub repository from Git, you’ll need to authenticate with GitHub using either HTTPS or SSH.
Note: You can authenticate to GitHub using GitHub CLI, for either HTTP or SSH. For more information, see gh auth login .
Connecting over HTTPS (recommended)
Connecting over SSH
If you clone with SSH, you must generate SSH keys on each computer you use to push or pull from GitHub.
Congratulations, you now have Git and GitHub all set up! You may now choose to create a repository where you can put your projects. This is a great way to back up your code and makes it easy to share the code around the world. For more information see «Create a repository».
You can create a copy of a repository by forking it and propose the changes that you want to see without affecting the upstream repository. For more information see «Fork a repository.»
Each repository in GitHub is owned by a person or an organization. You can interact with the people, repositories, and organizations by connecting and following them on GitHub. For more information see «Be social.»
GitHub has a great support community where you can ask for help and talk to people from around the world. Join the conversation on Github Support Community.
Help us make these docs great!
All GitHub docs are open source. See something that’s wrong or unclear? Submit a pull request.
Источник
Using github on linux
Installing and using Git and GitHub on Linux
Installing and using Git and GitHub on Ubuntu Linux
Introduction:
Git is a distributed revision control system with an emphasis on speed, data integrity, and support for distributed, non-linear workflows. Git is commonly used for source code management (SCM) and has become more used than old VCS systems like SVN.
GitHub is a Web-based Git repository hosting service, which offers all of the distributed revision control. Unlike Git, which is strictly a command-line tool, GitHub provides a Web-based graphical interface. GitHub is used for ‘version control’. This means that GitHub is used for software development projects when more than a person(or a group) is working on it. What GitHub does is that it creates a cloud-based centralized repository for everyone working in the group and allows everyone working on the project to update the information.
Installing Git on Ubuntu Linux
Goto www.github.com and sign into your account. If you’re a new user, you can simply sign-up.
You’ll have a username from here. Let us say that it’s your_username
github-homepage
Configuring Git:
Go back to the terminal and type this to configure git
Now type this to link your email too.
We will define our default editor. We are using gedit for this.
Describe —global flag
Multiple repositories can be created in a single machine. If you use the —global flag, the setting will applied to all the repositories of the machine. If you want this identity only for specific repository, then do not use —global flag.
Using Git:
Go to your github account and create a repository with a name(lets say name of your project). We are creating a repository with the name myproject.
github-new-repository
Git Repository
Git repository is a folder where all the data of our project will be stored. It can be located on the local machine or on a remote machine.
Difference between normal folder and Git repository
Normal folder contains only files and directories.
Git repository contains files and directories along with their complete history.
Make a folder with the name of your project and change your current directory to that directory.
Now we will set up the remote, which tells git where the repository is located.
We have now configured and installed git and, created and configured a repository. Lets say we have a simple html files in the myproject folder for demonstration and we want it to share it with a friend who is working on the same project.
To add this file we will type.
Or if we have a lot of files to be transferred from the folder to our git account, then we can use the command.
So we will make some changes in the same file and will check the result.
Git Staging Area:
Staging area is a file that stores information of the changes that need to be committed. The file contents should be added to the staging area, before committing them. Older git versions used the term index instead of staging area.
We will again run below mentioned command to add changes in staging area.
Now file changes are ready to be committed.
When we attain a particular stage, we can save our work in the repository. This is called commit. Each commit is saved with the information of username, email-id, date, time and commit message.
Now we will use git another useful command as shown below.
After commit we will have an ID which is a unique ID of 40 alpha-numeric characters. Git stores all the information in its database by the hash value. Git commits are identified by the SHA-1 hash.
Next, we need to push the commit that we just made on to the repository at github
It would automatically ask you for your username and password for github. After entering the details, go to github and refresh. The files would get added there.
We have successfully transferred a file on your github account. Now lets add one more file aboutme.txt and edit our file mypage.html. Following the same procedure we will first add the files, commit and then push them to the github account.
When we would go to our github account, we would see the entire hierarchy of the modification of the file. Here, we would see the changes we made to the mypage.html file in the respective commits.
github-second-commit
Now, Lets say one of the co-worker of the project needs to work on mypage.html. After making some changes, he wants to update the file on github.
First he would have to download the whole repository in which the file mypage.html is present into his system.
A folder named myproject gets downloaded with all the files in it. The necessary changes are made and then the file is similarly added, committed and pushed similarly as above.
So far, you’ve pushed your changes from a local repository to a remote repository and cloned a remote repository. We haven’t said anything about the «pull» command, though. Pushing changes to GitHub or BitBucket is great. But when other developers push their changes to a remote repository, you’ll want to see their changes on your computer. That is, you’ll want to pull their code to your local repository. To do so, run the following command:
Running «git pull» is enough to update your local repository.
Wait, but you said I could clone a repository. Why do I have to pull something?
That’s a valid question, so let’s clarify.
Cloning a repository is very different from pulling from a repository. If you clone a remote repository, Git will:
- Download the entire project into a specified directory; and
- Create a remote repository called origin and point it to the URL you pass.
The last item simply means that you don’t need to run «git remote add origin git@github.com:YourUsername/your-app.git» after cloning a repository. The «clone» command will add a remote origin automatically, and you can simply run «git push» from the repository.
When you run the «pull» command, Git will:
- Pull changes in the current branch made by other developers; and
- Synchronize your local repository with the remote repository.
The «pull» command doesn’t create a new directory with the project name. Git will only pull updates to make sure that your the local repository is up to date.
Conclusion:
Basically, that’s all you need to know about pushing, pulling, and cloning with Git. There are more tutorials that will go into deeper explanation of using Git and GitHub on linux command line, but this is a simple article to just get familiar with the concept.
Источник