- Как пользоваться GitHub на компьютере с Linux
- Установка git
- Синтаксис
- Создание проекта на локальном компьютере
- Отправка данных на GitHub
- Создание репозитория
- Заливаем проект в репозиторий на GitHub
- Получение файлов с GitHub
- Клонирование проекта
- Возможные ошибки
- 1. При попытке отправить данные на GitHub, получаем ошибку:
- jwebcat / gist:5122366
- This comment has been minimized.
- ddimitrioglo commented Nov 12, 2017
- This comment has been minimized.
- devpie commented Mar 2, 2018
- This comment has been minimized.
- dnanto commented May 26, 2019
- This comment has been minimized.
- ny0x696 commented May 27, 2019
- This comment has been minimized.
- lucasbasquerotto commented Aug 23, 2019
- This comment has been minimized.
- pushpdeep commented Oct 25, 2019
- This comment has been minimized.
- guillerglez88 commented Nov 14, 2019
- This comment has been minimized.
- littlejeem commented Dec 7, 2019
- This comment has been minimized.
- MagicJohnJang commented Feb 17, 2020 •
- This comment has been minimized.
- Darrenzzy commented May 27, 2020
- This comment has been minimized.
- tarpanpathak commented Jul 24, 2020
- This comment has been minimized.
- OctavioBR commented Aug 4, 2020
- This comment has been minimized.
- OctavioBR commented Aug 4, 2020
- This comment has been minimized.
- g0d0 commented Aug 5, 2020 •
- This comment has been minimized.
- trylaarsdam commented Aug 22, 2020
- This comment has been minimized.
- dienluong commented Aug 27, 2020
- How To Download Files From GitHub
- Downloading a File From GitHub
- Downloading GitHub Files Using Commands
- There’s a Better Way to Download Files
- Closing
Как пользоваться 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 — путь к нашему репозиторию.
Причина: проект ни разу не был зафиксирован (закоммичен).
Решение: добавляем комментарий к нашему проекту:
Источник
jwebcat / gist:5122366
wget —no-check-certificate —content-disposition https://github.com/joyent/node/tarball/v0.7.1 |
# —no-check-cerftificate was necessary for me to have wget not puke about https |
curl -LJO https://github.com/joyent/node/tarball/v0.7.1 |
This comment has been minimized.
Copy link Quote reply
ddimitrioglo commented Nov 12, 2017
This comment has been minimized.
Copy link Quote reply
devpie commented Mar 2, 2018
That’s great. Thanks.
This comment has been minimized.
Copy link Quote reply
dnanto commented May 26, 2019
This was driving me crazy, thanks!
This comment has been minimized.
Copy link Quote reply
ny0x696 commented May 27, 2019
Fantastic!! thank you
This comment has been minimized.
Copy link Quote reply
lucasbasquerotto commented Aug 23, 2019
This comment has been minimized.
Copy link Quote reply
pushpdeep commented Oct 25, 2019
This comment has been minimized.
Copy link Quote reply
guillerglez88 commented Nov 14, 2019
This comment has been minimized.
Copy link Quote reply
littlejeem commented Dec 7, 2019
This comment has been minimized.
Copy link Quote reply
MagicJohnJang commented Feb 17, 2020 •
This comment has been minimized.
Copy link Quote reply
Darrenzzy commented May 27, 2020
This comment has been minimized.
Copy link Quote reply
tarpanpathak commented Jul 24, 2020
This comment has been minimized.
Copy link Quote reply
OctavioBR commented Aug 4, 2020
For people who like the long, more understandable form of curl options to be used in scripts:
This comment has been minimized.
Copy link Quote reply
OctavioBR commented Aug 4, 2020
Don’t know why —remote-header-name is required. It works fine only with —location & —remote-name
This comment has been minimized.
Copy link Quote reply
g0d0 commented Aug 5, 2020 •
None of these examples work for me. 404 is returned.
This comment has been minimized.
Copy link Quote reply
trylaarsdam commented Aug 22, 2020
thanks for this!
None of these examples work for me. 404 is returned.
This likely means your URL is invalid (the file isn’t on the server)
This comment has been minimized.
Copy link Quote reply
dienluong commented Aug 27, 2020
(HTTP) This option tells the -O, —remote-name option to use the server-specified Content-Disposition filename instead of extracting a filename from the URL.
If the server specifies a file name and a file with that name already exists in the current working directory it will not be overwritten and an error will occur. If the server doesn’t specify a file name then this option has no effect.
There’s no attempt to decode %-sequences (yet) in the provided file name, so this option may provide you with rather unexpected file names.
WARNING: Exercise judicious use of this option, especially on Windows. A rogue server could send you the name of a DLL or other file that could possibly be loaded automatically by Windows or some third party software.
Generally, one shouldn’t blindly use command options without knowing what they do.
Источник
How To Download Files From GitHub
If you’ve ever used GitHub before, you know that it’s not immediately clear on how to download files from the platform. It’s one of the more complicated platform, as it isn’t directly meant for direct file sharing, but for development instead. Granted, one of the big things about GitHub is that all of the public repositories are open source, and people are encouraged to contribute — there are private repositories, but these are generally used for development purposes within businesses that don’t want their code seen by the public. GitHub, however, still handles downloading files differently than other places.
So if you’re not entirely sure how you can download files from projects (or entire projects) from GitHub, we’re going to show you how. Let’s get started.
Downloading a File From GitHub
Most public repositories can be downloaded for free, without even a user account. This is because public repositories are considered to be codebases that are open source. That said, unless the owner of the codebase checks a box otherwise, their codebase can be downloaded onto your computer, packed into a .zip file.
- So, if you go to a public codebase — such as this Tip Calculator that I built — you’ll notice that in the top-right corner is a green button that says Clone or Download, click on the button.
- Then, in the dropdown, select Download ZIP. All of the files will begin downloading to your computer, usually in your Downloads folder.
- Then, open your Downloads folder on your computer and find the ZIP file. You’ll want to right-click it and choose the option that says Extract All…, Unzip, or Uncompress, and then select a folder where you want the files to end up.
- Finally, navigate to that selected folder, and you’ll find all of those Github files that we downloaded right there!
That’s a fairly small codebase, with only a couple of files in it. If you go to Wes Bos’ JavaScript 30 repository on Github, you’ll notice that — since it is a public repository — it can be downloaded the same way.
Downloading GitHub Files Using Commands
Alternatively, you can easily clone a file or repository using a few simple commands on GitHub. For this to work, you’ll need to install the Git tools. We’re going to be installing the same tip calculator from the command line in this demo.
- Copy the URL from your address bar or from the same menu where you downloaded the zip file from.
- Open up Git Bash, type in “cd Downloads” and hit Enter. This will take you to the Downloads folder in the command window, you can also type whatever file location you want to save the file in.
- Now, type in “git clone https://github.com/bdward16/tip-calculator.git“and hit Enter.
- Using this method, the files are automatically unzipped when downloaded.
There’s a Better Way to Download Files
While the way we outlined is simple and straightforward, it’s most optimal for simply viewing the code files, not experimenting. If you’re planning on downloading GitHub files to experiment with, the best way would be to “fork” the project. A fork is simply your own copy of a repository.
Forking a repository comes with a number of benefits. It gives you your own copy on your GitHub account that allows you to freely experiment with changes without affecting the original project. For example, you could find a bug in my Tip Calculator or want to add your own features. So, you could “fork” my Tip Calculator, creating a copy on your GitHub account. Here, you could mess around the code and experiment with it without affecting the original project, because this would be your copy or “fork.”
Most commonly, forks are used to either propose changes to someone else’s project, like fixing a bug or adding a feature as we mentioned.
So, how do you fork a public repository? It’s actually quite easy. Before we get started, you need to create a free GitHub account, as you’ll need somewhere to store your fork. You can head to www.github.com and do this right now.
Once you have your account created, you can fork a public repository to your account.
- For example, you can head over to the public repository for Wes Bos’ 30 Days of JavaScript training course, and in the top-right corner, you’ll see a button that says Fork. Click the button.
- It could take a couple of seconds to a few minutes, but GitHub will then clone or “fork” that project over to your own GitHub account. Once it’s done, it’ll immediately show you the project under your GitHub username.
- To verify, you can click on your profile icon in the navigation bar at the top-right, and then select the option that says Your Repositories . In your list of repositories, you should see the JavaScript 30 course codebase.
Now, you can change and experiment with the code all you want, and it won’t affect the original project files of the original owner. If you change some code, fix a bug, or add a new feature, you can create something called a “Pull Request,” where that change can be discussed. If the original project owner likes the change — and it works properly — it can be merged into the original codebase as production code.
Closing
As you can see, downloading files and whole projects from GitHub is actually quite easy. In just a couple of minutes, you can have an entire project downloaded onto your computer, or even forked to your own GitHub account. It doesn’t take much to mess around with the code in your fork to see what affects what, and then eventually, you might even be able to create your first pull request! Happy coding!
Источник