- Как пользоваться GitHub на компьютере с Linux
- Установка git
- Синтаксис
- Создание проекта на локальном компьютере
- Отправка данных на GitHub
- Создание репозитория
- Заливаем проект в репозиторий на GitHub
- Получение файлов с GitHub
- Клонирование проекта
- Возможные ошибки
- 1. При попытке отправить данные на GitHub, получаем ошибку:
- how to wget a github file
- 4 Answers 4
- Shortest way to download from GitHub
- 4 Answers 4
- How to download a GitHub repo as .zip using command line
- 4 Answers 4
- Using cURL
- Download a .tgz instead of .zip
- Fastest way to download a GitHub project
- 8 Answers 8
Как пользоваться 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 — путь к нашему репозиторию.
Причина: проект ни разу не был зафиксирован (закоммичен).
Решение: добавляем комментарий к нашему проекту:
Источник
how to wget a github file
How to I download the actual file, and not the html?
I tried the following, but only get an html file:
4 Answers 4
The general problem is that github typically serves up an html page that includes the file specified along with context and operations you can perform on it, not the raw file specified. Tools like wget and curl will just save what they’re given by the web server, so you need to find a way to ask the web server, github, to send you a raw file rather than an html wrapper. This is true whether you use -o -O or >>. The «. //raw.git. » address in this particular test case is probably serving raw files, and pre-solving the OP’s problem as posted, which is why all of these answers work, but don’t solve the more generic problem. I can download a text file, or an html-wrapped version of it from the following urls. Note the differences between them and feel free to paste them in a new tab or new window in your browser as well.
raw link, if you right-click the [raw] button on the html page:
final url, after being redirected:
You can then download with either:
The simplest way would be to go to the github page of the content you want and right-click to get the [raw] link for each file. If your needs are more complex, requiring many files, etc. you may want to abandon wget and curl and just use git. It is probably a more appropriate tool for pulling data from git repositories.
Источник
Shortest way to download from GitHub
This is, how I download various master branches from GitHub, and I aim to have a prettier script (and maybe more reliable?).
Can this be shorten to one line somehow, maybe with tar and pipe?
Please address issues of downloading directly to the home directory
/ and having a certain name for the directory ( mv really needed?).
4 Answers 4
The shortest way that seems to be what you want would be git clone https://github.com/user/repository —depth 1 —branch=master
/dir-name . This will only copy the master branch, it will copy as little extra information as possible, and it will store it in
This will clone the files into new directory it creates:
Let’s start with the bash function I had handy for my own personal use:
You want the file to always be called master.zip and always be downloaded into your home directory, so:
However, there are a few things for you to consider:
1) My original script will give you a unique download zip file name for each download, based upon the name of the github repository, which is generally what most people really want instead of everything being called master and having to manually rename them afterwards for uniqueness. In that version of the script, you can use the value of $out_file to uniquely name the root directory unzipped tree.
2) If you really do want all downloaded zip files to be named
/master.zip , do you want to delete each after they have been unzipped?
3) Since you seem to always want everything put in directory
/myAddons , why not perform all the operations there, and save yourself the need to move the unzipped directory?
Источник
How to download a GitHub repo as .zip using command line
I am trying to download a .zip file from GitHub using the command line in Ubuntu. I am using wget command for it on a remote Ubuntu system.
I run wget
Now, when I am executing the command, it is downloading a file with text/html type and not the .zip file which I want.
Please tell me how to get the link to be given as the parameter of wget . Right now, I am just copying the link address of the button (using right click) and writing that as a wget parameter.
4 Answers 4
It does work, if you use the correct URL.
For a GitHub repo, there’s a zip at https://github.com/ / /archive/
.zip , so you can download it with:
This downloads the zipped repo for a given branch. Note that you can also replace the branch by a commit hash.
Using cURL
cURL’s -L flag follows redirects — it’s a default in wget.
Download a .tgz instead of .zip
You can also download a tarball with:
From the comments I saw you actually speak about GitHub.
It won’t work like this because:
Downloading a project on GitHub causes the GitHub server to first pack your project as zip and than forwarding you to a temporary link where you get your zip ..
this link will only work for a certain time and than GitHub will delete your zip file from their servers..
So what you get with wget is just the html page which would forward you as soon as your zip file is generated.
Источник
Fastest way to download a GitHub project
I need to download the source code of the project Spring data graph example into my box. It has public read-only access. Is there is an extremely fast way of downloading this code?
I have no idea of working on GitHub/committing code and most tutorials out there on the web seems to assume that «I would want to setup a project in GitHub» and inundate me with 15-20 step processes. To me, if a source repository is available for the public, it should take less than 10 seconds to have that code in my filesystem.
Tutorials that provide me with 15-20 step processes:
I need something very very very simple. Just pull the source code, and I am more interested in seeing the source code and not learn GitHub.
Are there any fast pointers/tutorials? (I have a GitHub account.)
8 Answers 8
When you are on a project page, you can press the ‘Download ZIP’ button which is located under the «Clone or Download» drop down:
This allows you to download the most recent version of the code as a zip archive.
If you aren’t seeing that button, it is likely because you aren’t on the main project page. To get there, click on the left-most tab labeled «<> Code».
To me if a source repository is available for public it should take less than 10 seconds to have that code in my filesystem.
And of course, if you want to use Git (which GitHub is all about), then what you do to get the code onto your system is called «cloning the repository».
It’s a single Git invocation on the command line, and it will give you the code just as seen when you browse the repository on the web (when getting a ZIP archive, you will need to unpack it and so on, it’s not always directly browsable). For the repository you mention, you would do:
The git: -type URL is the one from the page you linked to. On my system just now, running the above command took 3.2 seconds. Of course, unlike ZIP, the time to clone a repository will increase when the repository’s history grows. There are options for that, but let’s keep this simple.
I’m just saying: You sound very frustrated when a large part of the problem is your reluctance to actually use Git.
Источник