Как добавить git bash в visual studio code
установить git из https://git-scm.com/download/win
затем откройте visual studio code и откройте команду palate с помощью "ctrl+shift+p". Затем введите "открыть настройки пользователя", затем выберите "Открыть Настройки пользователя" из выпадающего меню.
затем эта вкладка откроется с настройками по умолчанию слева и вашими настройками справа
Теперь скопируйте эту строку код на вашу собственную страницу настроек (панель справа) и сохранить - "terminal.integrated.shell.windows": "C:\Program Files\Git\bin\bash.exe"
Примечание: "C:\Program Files\Git\bin\bash.exe" - это путь, где Баш.расположен исполняемый файл из git установки.
Теперь нажмите " ctrl+`", чтобы открыть терминал из vscode. И у тебя будет Баш -
нажмите и удерживайте Ctrl +', чтобы открыть терминал. Внутри терминала типа 'bash' без котировок использовать gitbash в терминале. Примечание: убедитесь, что на вашем компьютере установлен gitbash.
Если вы хотите использовать powershell снова, просто введите "powershell" без котировок в терминале. Для использования командной строки Windows введите "cmd"в терминале.
выбранная настройка будет использоваться по умолчанию.
1.) Установите git из https://git-scm.com/download/win
2.) откройте код visual studio и нажмите и удерживайте Ctrl +', чтобы открыть терминал.
3.) откройте команду небо с помощью "ctrl + shift+p".
4.) Тип-Выберите Оболочку По Умолчанию
5.) Выберите Git Bash из опций
6.) Нажмите на значок " + " в окне терминала
7.) Новый терминал теперь будет Git Bash терминал. Git это несколько секунд, чтобы загрузить Git Bash
8.) Теперь вы можете переключаться между различными терминалами, а также из выпадающего списка в терминале.
самый простой способ теперь (по крайней мере, от VSCode 1.22 on) - это ввести Shift-Ctrl-p открыть Командная Палитра и
теперь вы можете легко выбрать предпочтительную оболочку между теми, которые находятся в вашем пути:
для оболочек, которые не находятся в вашем % PATH%, см. другие ответы.
посмотреть полная ссылка на оболочку VSCode. Там много мясистых вещей.
я следовал в этом уроке от пола ДеКарло, чтобы использовать Bash из подсистемы Windows для Linux (WSL) вместо того, что поставляется с Git Bash для Windows. Шаги Sames, как указано выше в ответе, но вместо этого используйте приведенные ниже в настройках пользователя.
"terminal.integrated.shell.windows": "C:\Windows\sysnative\bash.exe",
это сработало для меня в первый раз. что является редкостью для этого материала.
Это, по крайней мере для меня, заставит VSCode открыть новое окно bash в качестве внешнего терминала.
что вам нужно сделать, если вы хотите интегрированную среду, это указать на внутри bin папка вашей установки git.
Так что конфиг должен сказать C:\\bin\sh.exe
для меня это единственная комбинация работала!
С git-bash.ехе как . shell.windows , каждый раз, когда Баш открывался снаружи VS!!
слава Богу, это сработало, наконец!! Кроме того, я планировал полностью уничтожить VS и переустановить его (что заставило меня переустановить все мои расширения и повторить мои настройки!)
это зависит от того, установили ли вы git bash только для текущего пользователя или для всех пользователей:
если он установлен на всех пользователей, затем поставить "terminal.integrated.shell.windows": "C:\Program Files\Git\bin\bash.exe" в настройках пользователя ( Ctrl + Comma ).
если он установлен только для текущего пользователя, то поставить "terminal.integrated.shell.windows": "C:\Users\\AppData\Local\Programs\Git\bin\bash.exe" в настройках пользователя ( Ctrl + Comma ).
если методы, перечисленные выше, не работают, то вы должны попробовать решение Кристера, который говорит -
что вам нужно сделать, если вы хотите интегрированной среды заключается в том, чтобы ВГ.exe-файл внутри папки bin вашей установки git.
так что конфиг должен сказать C:\\bin\sh.exe
Примечание: ВГ.exe и bash.exe кажутся мне совершенно одинаковыми. Между ними не должно быть никакой разницы.
добавить до Path переменные среды. Каталог-это %ProgramFiles%\Git\bin по умолчанию. Таким образом, вы можете получить доступ к Git Bash с помощью simply введя bash в каждом терминале, включая интегрированный терминал кода Visual Studio.
Как установить путь и переменные среды в Windows
я консультирую компанию fortune 50, и это печально Windows 7 и никаких привилегий администратора. Таким образом, Node / Npm / VS code и т. д.. были подтолкнуты к моей машине-я не могу много изменить и т. д..
для этого компьютера под управлением Windows 7
ниже мои новые настройки, один не работает закомментирован
Git - это система контроля версий, программа, которая позволяет хранить разные версии одного и того же документа, легко переключаться между ранними и поздними вариантами, вносить и отслеживать изменения.
GitHub — веб-сервис, основанный на системе Git, социальная сеть для разработчиков, которая помогает вести коллективную разработку IT-проектов и позволяет:
- публиковать и редактировать свой код;
- комментировать чужие наработки;
- следить за новостями других пользователей.
Git Bash — это приложение для сред Microsoft Windows, которое предоставляет эмуляцию bash (командной оболочки), используемую для запуска Git из командной строки.
После установки Git Bash эти утилиты будут установлены в папку C:\Program Files\Git\bin .
Для изменения терминала Visual Studio Code по умолчанию с Windows PowerShell на Git Bash необходимо:
- установить Git Bash на компьютер;
- выбрать терминал по умолчанию в окне Visual Studio Code, нажав клавишу F1 и набрав (выбрав) пункт меню Terminal: Select Default Profile ;
- в раскрывшемся окне выбрать Git Bash.
ВАЖНО! Git Bash должен быть установлен в папку C:\Program Files . При установке в другую папку подключить Git Bash к VS Code не получится. Кроме того, именования папок, с которыми вы будете работать в дальнейшем, должны быть на латинице и не содержать пробелов.
Можно также напрямую изменить настройки терминала по умолчанию в JSON файле.
Перейдите в меню File > Preferences > Settings (или нажмите Ctrl + , ), затем щелкните крайний левый значок в правом верхнем углу («Открыть настройки (JSON)»):
В окне настроек JSON измените строку " terminal.integrated.automationShell.windows " , указав расположение исполняемого файла bash.exe "C: \\ WINDOWS \\ System32 \\ bash.exe" :
Для работы с Git необходимо:
- зарегистрироваться на github.com ;
- установить Git на компьютер в папку C:\Program Files ;
- сгенерировать SSH ключи, введя в терминале Git Bash команду ssh-keygen -t rsa -b 4096 -C "your_mail@example.com" (подробнее здесь );
Основные команды Git Bash
clear — очистить консоль
Навигация
- pwd - показать текущий каталог;
- ls - показать файлы в данной папке (кроме скрытых);
- ls -f - показать все файлы в данной папке (включая скрытые);
- cd c:/ - перейти в конкретный каталог диска С:/;
- cd - - вернуться назад;
- cd .. - выйти на 1 уровень вверх;
- cd ../.. - выйти на 2 уровня вверх.
Создание каталогов
- mkdir - создать папку;
- cd !$ - перейти в только что созданную папку;
- mkdir -p - cоздать сразу несколько папок (лишних пробелов быть не должно);
- mkdir -p app/ - создать сразу несколько вложенных папок (лишних пробелов быть не должно).
Создание файлов
- touch index.html - создать файл index.html;
- touch app/ - создать несколько файлов (лишних пробелов быть не должно)
Удаление файлов
- rm test - удалить пустую папку test;
- rm -r test - удалить папку test с файлами внутри неё.
Перемещение файлов
- mv app1/*.* app2 - переместить все файлы из папки app1 в папку app2.
Коммит - сохранение, фиксация (в архиве, репозитарии и др.) изменений (снимков во времени) программного кода.
Visual Studio Code on Windows uses PowerShell by default as the integrated terminal. If you want to use Bash from Visual Studio Code, what steps should be followed?
27 Answers 27
Open Visual Studio Code and press and hold Ctrl + ` to open the terminal.
Open the command palette using Ctrl + Shift + P .
Type - Select Default Profile
Select Git Bash from the options
Click on the + icon in the terminal window
The new terminal now will be a Git Bash terminal. Give it a few seconds to load Git Bash
You can now toggle between the different terminals as well from the dropdown in terminal.
This worked for me. I tried all of the other guides by manually adding in the default bash but it just opened up a new terminal window every time. Many thanks
You no longer need to type in bash.exe path manually. This answer is deprecated. Now you can switch to bash directly, if you have git installed in the default path. If you installed git to a different path you need to use the below solution.
Then open Visual Studio Code and open the command palette using Ctrl + Shift + P . Then type "open user setting", and then select "Open User Settings" from the drop down menu.
Then this tab will open up with default settings on left and your settings on the right:
Now copy this line of code to your own settings page (the pane on the right hand side) and save - "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
Note: "C:\\Program Files\Git\bin\bash.exe" is the path where the bash.exe file is located from the Git installation. If you are using the Windows Subsystem for Linux (WSL) Bash shell, the path would be "C:\Windows\System32\bash.exe"
Now press Ctrl + ` to open up the terminal from Visual Studio Code. And you will have Bash -
Рано или поздно у разработчика наступает момент, когда разработка вида "хренак, хренак и в продакшен" уже не устраивает и требуются системы, которые бы работали как сохранения в игре, и в любой момент можно вернуться к определенному шагу разработки. Такие системы называют системами контроля версий, их очень много, но речь сегодня пойдет именно про 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
Установка в Windows
Скачайте exe-файл инсталлятора с сайта Git и запустите его. Это Git для Windows, он называется msysGit. Установщик спросит добавлять ли в меню проводника возможность запуска файлов с помощью Git Bash (консольная версия) и GUI (графическая версия). Подтвердите действие, чтобы далее вести работу через консоль в Git Bash. Остальные пункты можно оставить по умолчанию.
Проверим, что Git установлен.
После того, как все действия по установке завершены, убедимся, что Git появился в системе компьютера. Откройте терминал и введите git --version , должна появиться текущая версия программы на вашей машине. Эта проверка подходит для всех операционных систем.
Настройка Git
После установки производим настройку своего профиля вводя в терминал поочереди команды:
Заменив значения ВАШЕ_ИМЯ и АДРЕС вашими значениями.
После указания своих данных, можно их просмотреть:
Обратите внимание, что в командах, указанных выше, есть опция --global . Это значит, что такие данные будут сохранены для всех ваших действий в Git и вводить их больше не надо. Если вы хотите менять эту информацию для разных проектов, то в директории проекта вводите эти же команды, только без опции --global .
GITHUB
GitHub — веб-сервис, который основан на системе Git. Это такая социальная сеть для разработчиков, которая помогает удобно вести коллективную разработку IT-проектов. Здесь можно публиковать и редактировать свой код, комментировать чужие наработки, следить за новостями других пользователей. Именно в GitHub работаем мы, команда Академии, и студенты интенсивов.
Чтобы начать работу с GitHub, нужно зарегистрироваться на сайте, если вы ещё этого не сделали.
После того как у вас будет создан аккаунт в Github можно будет начать полноценно работать с ним.
Копирование репозитория Git в локальную папку
Для начала определим, что такое репозиторий. Это рабочая директория с вашим проектом. По сути, это та же папка с HTML, CSS, JavaScript и прочими файлами, что хранится у вас на компьютере, но находится на сервере GitHub. Поэтому вы можете работать с проектом удалённо на любой машине, не переживая, что какие-то из ваших файлов потеряются — все данные будут в репозитории при условии, что вы их туда отправите. Но об этом позже.
To get started with the GitHub in VS Code, you'll need to create a GitHub account and install the GitHub Pull Requests and Issues extension. In this topic, we'll demonstrate how you can use some of your favorite parts of GitHub without leaving VS Code.
If you're new to source control or want to learn more about VS Code's basic Git support, you can start with the Version Control topic.
Getting started with GitHub Pull Requests and Issues
Once you've installed the GitHub Pull Requests and Issues extension, you'll need to sign in. Follow the prompts to authenticate with GitHub in the browser and return to VS Code.
Setting up a repository
Cloning a repository
You can search for and clone a repository from GitHub using the Git: Clone command in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) or by using the Clone Repository button in the Source Control view (available when you have no folder open).
From the GitHub repository dropdown you can filter and pick the repository you want to clone locally.
Authenticating with an existing repository
Enabling authentication through GitHub happens when you run any Git action in VS Code that requires GitHub authentication, such as pushing to a repository that you're a member of or cloning a private repository. You don't need to have any special extensions installed for authentication; it is built into VS Code so that you can efficiently manage your repository.
When you do something that requires GitHub authentication, you'll see a prompt to sign in:
Follow the steps to sign into GitHub and return to VS Code. If authenticating with an existing repository doesn't work automatically, you may need to manually provide a personal access token. See Personal Access Token authentication for more information.
Note that there are several ways to authenticate to GitHub, including using your username and password with two-factor authentication (2FA), a personal access token, or an SSH key. See About authentication to GitHub for more information and details about each option.
Note: If you'd like to work on a repository without cloning the contents to your local machine, you can install the GitHub Repositories extension to browse and edit directly on GitHub. You can learn more below in the GitHub Repositories extension section.
Editor integration
Hovers
When you have a repository open and a user is @-mentioned, you can hover over that username and see a GitHub-style hover.
Suggestions
The issues that appear in the suggestion can be configured with the GitHub Issues: Queries ( githubIssues.queries ) setting. The queries use the GitHub search syntax.
You can also configure which files show these suggestions using the settings GitHub Issues: Ignore Completion Trigger ( githubIssues.ignoreCompletionTrigger ) and GitHub Issues: Ignore User Completion Trigger ( githubIssues.ignoreUserCompletionTrigger ). These settings take an array of language identifiers to specify the file types.
Pull requests
From the Pull Requests view you can view, manage, and create pull requests.
The queries used to display pull requests can be configured with the GitHub Pull Requests: Queries ( githubPullRequests.queries ) setting and use the GitHub search syntax.
Creating Pull Requests
Once you have committed changes to your fork or branch, you can use the GitHub Pull Requests: Create Pull Request command or the Create Pull Request button in the Pull Requests view to create a pull request.
A new Create Pull Request view will be displayed where you can select the repository and branch you'd like your pull request to target as well as fill in details such as the title, description, and whether it is a draft PR. If your repository has a pull request template, this will automatically be used for the description.
Once you select Create, if you have not already pushed your branch to a GitHub remote, the extension will ask if you'd like to publish the branch and provides a dropdown to select the specific remote.
The Create Pull Request view now enters Review Mode, where you can review the details of the PR, add comments, reviewers, and labels, and merge the PR once it's ready.
After the PR is merged, you'll have the option to delete both the remote and local branch.
Reviewing
Pull requests can be reviewed from the Pull Requests view. You can assign reviewers and labels, add comments, approve, close, and merge all from the pull request Description.
From the Description page, you can also easily checkout the pull request locally using the Checkout button. This will switch VS Code to open the fork and branch of the pull request (visible in the Status bar) in Review Mode and add a new Changes in Pull Request view from which you can view diffs of the current changes as well as all commits and the changes within these commits. Files that have been commented on are decorated with a diamond icon. To view the file on disk, you can use the Open File inline action.
The diff editors from this view use the local file, so file navigation, IntelliSense, and editing work as normal. You can add comments within the editor on these diffs. Both adding single comments and creating a whole review is supported.
When you are done reviewing the pull request changes you can merge the PR or select Exit Review Mode to go back to the previous branch you were working on.
Issues
Creating issues
Issues can be created from the + button in the Issues view and by using the GitHub Issues: Create Issue from Selection and GitHub Issues: Create Issue from Clipboard commands. They can also be created using a Code Action for "TODO" comments. When creating issues, you can take the default description or select the Edit Description pencil icon in the upper right to bring up an editor for the issue body.
You can configure the trigger for the Code Action using the GitHub Issues: Create Issue Triggers ( githubIssues.createIssueTriggers ) setting.
Working on issues
From the Issues view, you can see your issues and work on them.
By default, when you start working on an issue (Start Working on Issue context menu item), a branch will be created for you, as shown in the Status bar in the image below.
The Status bar also shows the active issue and if you select that item, a list of issue actions are available such as opening the issue on the GitHub website or creating a pull request.
Once you are done working on the issue and want to commit a change, the commit message input box in the Source Control view will be populated with a message, which can be configured with GitHub Issues: Working Issue Format SCM ( githubIssues.workingIssueFormatScm ).
GitHub Repositories extension
The GitHub Repositories extension lets you quickly browse, search, edit, and commit to any remote GitHub repository directly from within Visual Studio Code, without needing to clone the repository locally. This can be fast and convenient for many scenarios, where you just need to review source code or make a small change to a file or asset.
Opening a repository
Once you have installed the GitHub Repositories extension, you can open a repository with the GitHub Repositories: Open Repository. command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) or by clicking the Remote indicator in the lower left of the Status bar.
When you run the Open Repository command, you then choose whether to open a repository from GitHub, open a Pull Request from GitHub, or reopen a repository that you had previously connected to.
If you haven't logged into GitHub from VS Code before, you'll be prompted to authenticate with your GitHub account.
You can provide the repository URL directly or search GitHub for the repository you want by typing in the text box.
Once you have selected a repository or Pull Request, the VS Code window will reload and you will see the repository contents in the File Explorer. You can then open files (with full syntax highlighting and bracket matching), make edits, and commit changes, just like you would working on a local clone of a repository.
One difference from working with a local repository is that when you commit a change with the GitHub Repository extension, the changes are pushed directly to the remote repository, similar to if you were working in the GitHub web interface.
Another feature of the GitHub Repositories extension is that every time you open a repository or branch, you get the up-to-date sources available from GitHub. You don't need to remember to pull to refresh as you would with a local repository.
Switching branches
You can easily switch between branches by clicking on the branch indicator in the Status bar. One great feature of the GitHub Repositories extension is that you can switch branches without needing to stash uncommitted changes. The extension remembers your changes and reapplies them when you switch branches.
Remote Explorer
You can quickly reopen remote repositories with the Remote Explorer available on the Activity bar. This view shows you the previously opened repositories and branches.
Create Pull Requests
If your workflow uses Pull Requests, rather than direct commits to a repository, you can create a new PR from the Source Control view. You'll be prompted to provide a title and create a new branch.
Once you have created a Pull Request, you can use the GitHub Pull Request and Issues extension to review, edit, and merge your PR as described earlier in this topic.
Virtual file system
Without a repository's files on your local machine, the GitHub Repositories extension creates a virtual file system in memory so you can view file contents and make edits. Using a virtual file system means that some operations and extensions which assume local files are not enabled or have limited functionality. Features such as tasks, debugging, and integrated terminals are not enabled and you can learn about the level of support for the virtual file system via the features are not available link in the Remote indicator hover.
Extension authors can learn more about running in a virtual file system and workspace in the Virtual Workspaces extension author's guide.
Continue Working on.
Sometimes you'll want to switch to working on a repository in a development environment with support for a local file system and full language and development tooling. The GitHub Repositories extension makes it easy for you to clone the repository locally or into a Docker container (if you have Docker and the Microsoft Docker extension installed) with the GitHub Repositories: Continue Working on. command available from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) or by clicking on the Remote indicator in the Status bar.
If you are using the browser-based editor, the "Continue Working On. " command has the options to open the repository locally or within a cloud-hosted environment in GitHub Codespaces.
Читайте также: