Как запустить git в командной строке windows

I've got what I'm hoping is a simple question, but I haven't been able to find the answer yet. I would like to launch Git Bash from a Windows batch file. Here is what I tried so far: Launched Gi...

I’ve got what I’m hoping is a simple question, but I haven’t been able to find the answer yet. I would like to launch Git Bash from a Windows batch file. Here is what I tried so far:

  1. Launched Git Bash from Win 7 Start button

  2. Used CTRL+ALT+DEL to identify the process as «sh.exe»

  3. Launched sh.exe from batch file using start command

     start sh.exe
    

However, this does not launch the full Git Bash environment. Git Bash usually has «MINGW32» in the title bar, but sh.exe has a full path to … Gitbinsh.exe. It feels to me like there are some overlays or dependencies that I’m not aware of possibly, that also need to be loaded (pulled in? imported?).

This was one of the top results I found through searching the web, but it doesn’t make complete sense to me and I’m not sure if it applies exactly to my situation:

Running git from Windows Cmd line: Where are key files?

I’m a beginner in the world of Windows batch scripting.

Squashman's user avatar

Squashman

13.5k5 gold badges26 silver badges36 bronze badges

asked Jun 25, 2013 at 16:44

Eric Hepperle - CodeSlayer2010's user avatar

3

If you want to launch from a batch file:

  • for x86

    start "" "%SYSTEMDRIVE%Program Files (x86)Gitbinsh.exe" --login
    
  • for x64

    start "" "%PROGRAMFILES%Gitbinsh.exe" --login
    

lanoxx's user avatar

lanoxx

11.2k10 gold badges85 silver badges138 bronze badges

answered Jun 25, 2013 at 20:11

Endoro's user avatar

7

I’m not sure exactly what you mean by «full Git Bash environment», but I get the nice prompt if I do

"C:Program FilesGitbinsh.exe" --login

In PowerShell

& 'C:Program FilesGitbinsh.exe' --login

The --login switch makes the shell execute the login shell startup files.

answered Jun 25, 2013 at 16:50

Klas Mellbourn's user avatar

Klas MellbournKlas Mellbourn

41.2k22 gold badges139 silver badges156 bronze badges

3

I prefer to use git-bash.exe instead of sh.exe.

start "" "%ProgramFiles%Gitgit-bash.exe" -c "tail -f /c/Windows/win.ini"

You can stop closing the window when call /usr/bin/bash --login -i in the end;

start "" "%ProgramFiles%Gitgit-bash.exe" -c "echo 1 && echo 2 && /usr/bin/bash --login -i"

Note: I’m not sure this is a good way :)

answered Mar 14, 2016 at 1:15

kujiy's user avatar

kujiykujiy

5,5791 gold badge29 silver badges34 bronze badges

4

I prefer, putting git in environment variable and just calling

c:Users[myname]>sh
or 
c:Users[myname]>bash

Steps to create Environment variable (Win7)

  • From the desktop, right click the Computer icon.
  • Choose Properties from the context menu.
  • Click the Advanced system settings link.
  • Click Environment Variables.
  • In the section User variables, hit button NEW, put variable name as GIT_HOME, value as (folder-where-you-installed-git).

    • for me it is was c:toolsgit, others maybe have C:Program FilesGit
  • find the PATH environment variable and select it. Click Edit. (If the PATH environment variable does not exist, click New).

  • In the Edit window, add a new value %GIT_HOME% and %GIT_HOME%bin. Click OK. Close all remaining windows by clicking OK.
  • [Make sure you close the CMD which you want use for git]
  • open new Command prompt, and just type sh or bash or git-bash

Abdulaziz Hamdan's user avatar

answered Jul 24, 2018 at 23:37

old-monk's user avatar

old-monkold-monk

7698 silver badges20 bronze badges

2

You can add git path to environment variables

  • For x86

%SYSTEMDRIVE%Program Files (x86)Gitbin

  • For x64

%PROGRAMFILES%Gitbin

Open cmd and write this command to open git bash

sh --login

OR

bash --login

OR

sh

OR

bash

You can see this GIF image for more details:

https://media1.giphy.com/media/WSxbZkPFY490wk3abN/giphy.gif

answered Jun 13, 2020 at 23:18

Eng_Farghly's user avatar

Eng_FarghlyEng_Farghly

1,6211 gold badge23 silver badges30 bronze badges

To access the GIT BASH with the command line.

Simply visit the Git installation directory.

In my case it was.

C:programGitbinsh.exe

Copy and paste that path to an environment variable.
enter image description here

Open command prompt and type bash

enter image description here

BOOM..! now you have successfully accessed the GIT BASH from the command prompt.

answered Feb 10, 2022 at 1:18

mufazmi's user avatar

mufazmimufazmi

1,0414 gold badges19 silver badges36 bronze badges

start "" "%SYSTEMDRIVE%Program Files (x86)Gitbinsh.exe" --login -i

Git bash will get open.

Gwenc37's user avatar

Gwenc37

2,0547 gold badges17 silver badges22 bronze badges

answered May 8, 2014 at 11:59

user3616334's user avatar

https://stackoverflow.com/a/33368029/15789

I have posted an answer here.

Open a Windows command window, and execute this script. If there is a change in your working directory, it will open a bash terminal in your working directory, and display the current git status. It keeps the bash window open, by calling exec bash.

If you have multiple projects you may create copies of this script with different project folder, and call it from a main batch script.

Community's user avatar

answered Oct 27, 2015 at 12:32

RuntimeException's user avatar

RuntimeExceptionRuntimeException

1,5832 gold badges23 silver badges31 bronze badges

I used the info above to help create a more permanent solution. The following will create the alias sh that you can use to open Git Bash:

echo @start "" "%PROGRAMFILES%Gitbinsh.exe" --login > %systemroot%sh.bat

answered Jul 29, 2018 at 14:37

dpate's user avatar

dpatedpate

312 bronze badges

1

Windows

Git bash default location C:Program FilesGitbin

So copy this folder path and paste it inside environment variables setting under system variables.

enter image description here

start -> Environment Variables

enter image description here

select Environment variable

enter image description here

Create a new environment variable like this

enter image description here

Add environment variable gtbash %gtbash% in the path variable

enter image description here

Now check by taking a new command prompt and typing sh (close already opened terminal or cmd)

enter image description here

Now live

something like this(GIF):

enter image description here

answered Feb 12, 2022 at 10:29

lava's user avatar

lavalava

4,9902 gold badges27 silver badges26 bronze badges

0

The answer by Endoro has aged and I’m unable to comment;

# if you want to launch from a batch file or the command line:

start "" "%ProgramFiles%Gitbinsh.exe" --login

answered Apr 12, 2016 at 13:03

ThaJay's user avatar

ThaJayThaJay

1,6871 gold badge17 silver badges30 bronze badges

If you want to start a «Git Gash» window from «Git Bash» window, so «start bash» will do the work in windows 10.

answered Nov 25, 2022 at 12:24

Ali Darwish's user avatar

1

Первые шаги в GIT + GITHUB + VS CODE 👶

Рано или поздно у разработчика наступает момент, когда разработка вида «хренак, хренак и в продакшен» уже не устраивает и требуются системы, которые бы работали как сохранения в игре, и в любой момент можно вернуться к определенному шагу разработки. Такие системы называют системами контроля версий, их очень много, но речь сегодня пойдет именно про GIT.

Что такое GIT

Git — система управления контроля версиями, репозитории Git содержат файлы, историю, конфигурации управляемые Git. Данные могут отправляться из локальной папки в Git репозиторий и обратно, локальное состояние подразумевает рабочую папку которая содержит измененные файлы готовые для помещения в .git каталог, при помещении в данный каталог — Commit, указываются комментарии к данному коммиту, что по факту является историей, удаленный репозиторий содержит ветки Branches, основная ветка называется Master, данные могут отправляться как в Master, так и другие ветки (ответвления) проекта.

GIT является одной из самых популярных систем. Её отличие от других программ — отсутствие графической версии. Поэтому работа с Git ведётся через командную строку. В разных операционных системах свои программы для взаимодействия с Git.

В Windows их две: PowerShell и cmd.exe. В Ubuntu это Terminal. Самая популярная программа на macOS тоже называется Terminal. Если вам не подходит встроенная в систему программа для работы с командной строкой, вы можете поставить свою. Например, написанную на JavaScript программу Hyper, которая работает на любой операционной системе. На Windows популярны программы Cmder и Git Bash, а на macOS — iTerm.

В мире разработки такие программы называют «терминал» или «консоль». А работает это так: мы вводим команду и получаем реакцию машины: сообщение об ошибке, запрос на подтверждение информации, результат выполненных действий.

Установка GIT

Если вы ранее не работали с GIT, то для начала его нужно установить. В зависимости от системы нужно выбрать свой вариант

Установка GIT в Linux (Ubuntu)

В зависимости от вашего дистрибутива Linux требуется установить через консоль, например в убунту эта команда будет иметь следующий вид:

Команды для других дистрибутивов можно посмотреть здесь.

Установка на macOS

  • Скачиваем Git со страницы проекта.
  • Запускаем загруженный файл.
  • Система может показать окно с ошибкой, где будет написано, что файл скачан с неавторизованного сайта и инсталлятор не может быть запущен. В таком случае нужно зайти в «Системные настройки» — «Безопасность» (Security and Privacy), в появившемся окне будет сообщение об ошибке и кнопка Open anyway (Всё равно открыть). Нажимаем.
  • Система покажет окно, уточняющее хотите ли вы запустить установку. Подтверждаем действие.
  • Установщик проведёт через все необходимые шаги.

Установка в Windows

Скачайте exe-файл инсталлятора с сайта Git и запустите его. Это Git для Windows, он называется msysGit. Установщик спросит добавлять ли в меню проводника возможность запуска файлов с помощью Git Bash (консольная версия) и GUI (графическая версия). Подтвердите действие, чтобы далее вести работу через консоль в Git Bash. Остальные пункты можно оставить по умолчанию.

Проверим, что Git установлен.

После того, как все действия по установке завершены, убедимся, что Git появился в системе компьютера. Откройте терминал и введите git --version, должна появиться текущая версия программы на вашей машине. Эта проверка подходит для всех операционных систем.

Настройка Git

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

git config --global user.name "ВАШЕ_ИМЯ"
git config --global user.email АДРЕС

Заменив значения ВАШЕ_ИМЯ и АДРЕС вашими значениями.

После указания своих данных, можно их просмотреть:

git config --global --list

Обратите внимание, что в командах, указанных выше, есть опция --global. Это значит, что такие данные будут сохранены для всех ваших действий в Git и вводить их больше не надо. Если вы хотите менять эту информацию для разных проектов, то в директории проекта вводите эти же команды, только без опции --global.

GITHUB

GitHub — веб-сервис, который основан на системе Git. Это такая социальная сеть для разработчиков, которая помогает удобно вести коллективную разработку IT-проектов. Здесь можно публиковать и редактировать свой код, комментировать чужие наработки, следить за новостями других пользователей. Именно в GitHub работаем мы, команда Академии, и студенты интенсивов.

Чтобы начать работу с GitHub, нужно зарегистрироваться на сайте, если вы ещё этого не сделали.

После того как у вас будет создан аккаунт в Github можно будет начать полноценно работать с ним.

Копирование репозитория Git в локальную папку

Для начала определим, что такое репозиторий. Это рабочая директория с вашим проектом. По сути, это та же папка с HTML, CSS, JavaScript и прочими файлами, что хранится у вас на компьютере, но находится на сервере GitHub. Поэтому вы можете работать с проектом удалённо на любой машине, не переживая, что какие-то из ваших файлов потеряются — все данные будут в репозитории при условии, что вы их туда отправите. Но об этом позже.

Копировать или клонировать репу c GitHub можно по HTTPS или SSH.

Команда для копирования репозитория:

git clone ССЫЛКА_НА_РЕПОЗИТОРИЙ

После клонирования переходим в папку репозитория:

Смотрим статус:

Добавление данных в Git или коммит (commit)

Создаем файл с текстом:

echo "This example Git text file" > example.txt

Смотрим статус:

Видим, что у нас есть файл готовый для загрузки в Git, добавляем его в репозиторий:

Снова смотрим статус, видим что у нас появился новый файл example.txt, добавляем данный файл в репозиторий используя git commit:

git commit -m "This first example text file"

Отправка данных в онлайн Git репозиторий

Отправить данные в репу можно используя команду git push:

После ввода аутентификационных данных, произойдет отправка в онлайн репозиторий, после чего можно обновить страницу на GitHub дабы убедиться в том, что новый файл добавлен в него (репозиторий).

Обратите внимание, что если вы используете двухфакторную авторизацию на github и являетесь пользователем linux, то вам нужно в настройках, в разделе «Developers setting» создать новый Personal access tokens и данный токкен использовать вместо пароля при аутентификации.

VISUAL STUDIO CODE

Данное ПО является хорошим выбором для комфортной работы с GIT и GITHUB. В VS Code есть встроенный терминал, который можно вызвать с помощью комбинации клавиш:

Внутри данного терминала вы можете использовать теже команды для работы с GIT которые были описаны выше.

Настройка терминала VS Code в Windows

По умолчанию консоль VS Code в Windows запускает стандартную командную строку Windows, которая не может работать с GIT, чтобы все работало нужно запустить терминал bash, для этого выполним следующие действия:

  1. Убедимся, что ранее нами был скачан и установлен git, подробнее данный процесс был описан выше.
  2. Запускаем Visual Studio Code.
  3. Зажимаем сочетание клавиш Ctrl + Shift + P вводим open user setting и из выпадающего меню выбираем Open User Settings.
  4. В параметры поиска вводим terminal.integrated.shell.windows и заменяем cmd.exe на C:\Program Files\Git\bin\bash.exe (если вы установили git в другую директорию то ссылка будет иметь вид относительно установленной вами директории).
  5. Перезагружаем Visual Stuio Code
  6. Открываем терминал и проверяем, что запущен bash терминал

Полезные ссылки по данной теме

sys-adm.in/programming/623-git-for-beginning.html

htmlacademy.ru/blog/187-git-console

Using Git

To use Git on the command line, you will 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 do not 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 do not need to work with files locally, GitHub lets you complete many Git-related actions directly in the browser, including:

  • Creating a repository
  • Forking a repository
  • Managing files
  • Being social

Setting up Git

  1. Download and install the latest version of Git.

    Note: If you are using a Chrome OS device, additional set up is required:

    1. Install a terminal emulator such as Termux from the Google Play Store on your Chrome OS device.
    2. From the terminal emulator that you installed, install Git. For example, in Termux, enter apt install git and then type y when prompted.
  2. Set your username in Git.

  3. Set your commit email address in Git.

Authenticating with GitHub from Git

When you connect to a GitHub repository from Git, you will 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)

If you clone with HTTPS, you can cache your GitHub credentials in Git using a credential helper. For more information, see «Cloning with HTTPS urls» and «Caching your GitHub credentials in Git.»

Connecting over SSH

If you clone with SSH, you must generate SSH keys on each computer you use to push or pull from GitHub. For more information, see «Cloning with SSH urls» and «Generating a new SSH key.»

Next steps

You now have Git and GitHub all set up. You may now choose to create a repository where you can put your projects. Saving your code in a repository allows you to back up your code and share it around the world.

  • Creating a repository for your project allows you to store code in GitHub. This provides a backup of your work that you can choose to share with other developers. For more information, see “Create a repository.».

  • Forking a repository will allow you to make changes to another repository without affecting the original. For more information, see «Fork a repository.»

  • Each repository on 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 Community.

Понравилась статья? Поделить с друзьями:
  • Как запустить git bash на windows
  • Как запустить geometry dash на windows 10
  • Как запустить generals contra 009 на windows 10
  • Как запустить gears of war ultimate edition на windows 10
  • Как запустить gears of war 4 на windows 10 1909