Как запустить bash в windows
Перейти к содержимому

Как запустить bash в windows

  • автор:

Bash shell running within Windows using Microsoft’s WSL (Windows Subsystem for Linux)

NOTE: Content here are my personal opinions, and not intended to represent any employer (past or present). “PROTIP:” here highlight information I haven’t seen elsewhere on the internet because it is hard-won, little-know but significant facts based on my personal research and experience.

June 2017 was the first “beta” release of Microsoft’s WSL (Windows Subsystem for Linux).

Around May 2019, Microsoft released WSL2 (version 2).

WSL is so much simpler than Cygwin

VIDEO and BLOG: Scott Hanselman explains it all: VS Code with Remote Extension, Docker, and the Windows Terminal.

Architecture

The diagram for WSL1: (TODO: Update for WSL2 needed)

bash-windows-wsl file-system-graphic-1024x547

gcc is installed by . bash, git can be installed using Choclately.

Lxcore.sys is the driver that recognizes Bash commands and other Linux utilities such as chmod to change permissions.

VFS is the Virtual File System.

From inside Bash, DrvFS gets to Windows.

From inside Windows, VolFS gets to Linux symbolic files and its case sensitivity.

NTFS (New Technology File System) is the file system controlling hard drives.

CAUTION: WSL provides no GPU support, so it can’t run Linux GUI programs such as Gnome, KDE, etc.

Got 64-bit?

Verify your PC’s CPU architecture and Windows version/build number:

Start: Click the Windows icon/keyboard key to open Settings, System, About (at the bottom of the list).

Windows 10: bash-windows-build-951x388

Get a newer computer if you don’t see:

System type 64-bit operating system, x64-based processor.

The technical requirement is that WSL currently runs “ELF64 Linux binaries”.

If you have configured PowerShell to run commands, get your Windows Server build number within PowerShell:

Get the installer: NOTE: We’re not using the Register to be in the Windows Insider Build.

  • Ubuntu-18.04 — CanonicalGroupLimited.Ubuntu18.04onWindows_1804.2018.817.0_x64__79rhkp1fndgsc
  • Ubuntu 18.04 ARM for running on Raspberry Pi?
  • Ubuntu-16.04 — Ubuntu_1604.2019.523.0_x64.appx
  • Debian GNU/Linux — DebianGNULinux_1-1-3-0_x64__76v4gfsz19hv4
  • Kali Linux
  • OpenSUSE Leap 42
  • SUSE Linux Enterprise Server 12
  • Fedora Remix for WSL (licensed)
  • Pengwin is paid/licensed. Based on Debian.
  • WLinux .

Virtualization

Virtualization must be enabled in the computer bios, instructions for this vary between manufacturers but it’s usually a simple on/off listing in the BIOS.

Enable WSL Windows Feature

Press the Windows Start button and immediately type in the search box that appears:

Type enough until the option appears in the menu, then click on the option.

Wait a while for all items to appear.

  1. Scroll down to check “Windows Subsystem for Linux”, then click OK to exit dialog, then Restart your computer.

(This option was added since the “Anniversary” and “Creators Update” of Windows 10.)

  1. Click the Windows Start and get in the Microsoft Window Store to install the new Windows Terminal. It is like tmux — it makes it easy to open multiple panes with different prompts for bash, command prompt and PowerShell.

Following instructions at https://docs.microsoft.com/en-us/windows/wsl/wsl2-install, in PowerShell, enable the ‘Virtual Machine Platform’ optional component (whatever that means):

Confirm whether Windows Subsystem for Linux is enabled in PowerShell:

The response I got:

Set Linux distro to be backed by WSL 2

PROTIP: WSL provides a choice of Linux distributions. For a list:

PROTIP: Ubuntu was the first distro tested with WSL, so it’s probably the most well tested. But it’s not supported by Windows 10 S. Both Ubuntu and Debian make use of the apt-get (Advanced Packaging Tool) package manager and dpkg command.

BTW Ubuntu is a Linux distribution from Canonical, Inc. which also created Virtualenv for Python.

Kali Linux is used by security researchers (not for production use).

Ubuntu version/release

In a web browser, know what the latest version of Ubutu is:

Note there is a name for each release.

WARNING: Time is needed for integration into Windows, so WSL probably does not support the very latest version of Ubuntu.

Search for Ubuntu:

Scroll to see the latest version of Ubuntu for Windows (such as 22.4.5 LTS).

Once installed, the ‘Install’ button will change to ‘Launch’, click the ‘Launch’ button.

One can, but don’t: alternately, download the “.appx” installer by constructing the curl command for the Ubuntu version listed above, such as:

This is instead of the Invoke-WebRequest PowerShell command or Microsoft Store for Business used within enterprises.

Set the distribution code for the Linux distro downloaded (I don’t know why):

Verify what versions of WSL your distros are using:

Make WSL 2 your default architecture (as if you’ll ever want to go back):

Open Task Manager to see it.

Ubuntu Install, Launch, and configure

Scroll to “Ubuntu on Windows”. Right-click and select “Pin to Start”

wsl-ubuntu-pin-259x170

Repeat to “Run as Administrator” or Launch a new instance.

  1. Enter a username your make up.

PROTIP: The WSL user is not “root” with admin priviledges.

  1. PROTIP: Get the password copied into your Clipboard from 1Password or other Password Manager, then paste onto the screen.

A shortcut is added to your start menu named:

Bash on Ubuntu on Windows

Click the shortcut.

By default, the prompt is your Linux user name @ your machine name:/mnt/c/Users/%USERNAME%$

You should now see a pop-up window showing Ubuntu, such as this example:

You brave enough:

View details of the Linux distro currently running:

The version at time of this writing:

### Linux Folders and variables

See where Ubuntu is installed using a Windows system variable referenced using a Windows % wrapper rather than Bash $ prefix:

Note the directory is marked as a hidden system folder. That’s a clue that you should not modify files in your bash environment using Windows File Explorer, console, or apps.

Creating and/or modifying files in this location using Windows tools and apps corrupts the system because it is read-locked. Here is an explanation.

Type your admin password for all subsequent commands:

Install latest release of kubectl on Ubuntu:

Install latest release of Minikube:

If you see this error: Exiting due to GUEST_MISSING_CONNTRACK: Sorry, Kubernetes 1.25.3 requires conntrack to be installed in root’s path

In the Ubuntu Linux terminal, verify:

In the Ubuntu Linux terminal, start minikube:

Alternately, (from CHATGPT4) run the dockerd server:

Install & Configure Utilities

TODO: Use brew to install additional utilities: git, Python/pip, tree, jq, etc.

Use pip to install Virtualenv.

Install keyboard aliases to use custom commands:

NOTE: To run Python for Selenium controlling Firefox, install Xming with gekoDriver.

Profile to define prompt

Open the Bash command prompt</strong> (click Windows Start and type Bash until you can select it from the list that arises):

NOTE: You can run Linux binaries such as ls from the Windows Command Prompt (CMD or PowerShell) by invoking wsl.exe there. These are called interop features.

Open the Visual Studio Code text editor to the file in the $HOME folder, which is what

stands for, just like in macOS:

By default, WSL reads and executes commands from the file /etc/profile if that file exists. After reading that file, it looks for

/.profile, in that order, and reads and executes commands from the first one that exists and is readable. It skips the other files if one is found.

Define keyboard aliases in a .bash_aliases file in the .bashrc file *

My list is in https://github.com/wilsonmar/git-utilities/master/aliases.sh

LinuxBrew vs. Homebrew for MacOS

Install the LinuxBrew fork of Homebrew for macOS*

“I found some apps that didn’t work well from apt-get worked flawlessly when installed with brew, like zplug. Inversely, I couldn’t get ranger to work with brew but got it working with apt-get. This very conveniently gives you multiple options for installing a package, potentially skipping the step of Googling vague errors.

To fix the patchelf error:

Linux commands

Get to know the built-in Linux commands: cat, cd, chmod, chown, curl, df, diff, echo, exit, find, finger, grep, groups, gzip, head, history, kill, less, ls, man, mkdir, mv, passwd, ping, ps, pwd, shutdown, ssh, sudo, tail, tar, top, uname, w, whoami. There’s also cp.

Rather than a translation layer built by the WSL 1 team, WSL 2 includes its own open-sourced Linux kernel with full system call compatibility with the LTS Linux kernel. WSL2 does not work under HyperV.

Sean Dearnaley points out that since macOS currently doesn’t have good GPU support, if Windows introduces GPU support for WSL, Windows machines could become a very powerful machine learning development platform when running Nvidia CUDA based apps.

pwd file storage mounts

To list drives mounted:

The response is the drives:

For the purpose of this tutorial, create folder dev/project for use by both Windows and Linux tools:

You can also make whatever directory name you want.

PROTIP: Use $HOME or

to reference your home folder:

Unlike/users on macOS, the folder above user accounts is:

Open Windows Explorer to view files from both Windows and from Bash:

Access files from both Windows and from Bash as:

Run a Linux utility such as disk usage of the current folder (represented by a dot):

The response is like 56K .

View the manual on the du command:

PROTIP: Remember this move whenever you see that “:” in the lower-left corner:

type q to quit out.

VSCode Extensions

In VSCode, “Trust and install” extensions Docker (from Microsoft), “Dev Containers”, “Kubernetes”.

VIDEO: Run and debug your Linux-based applications from within VSCode in Windows. Edit files in WSL or the mounted Windows filesystem (/mnt/c) without worrying about pathing issues, binary compatibility, or other cross-OS challenges.

Read the FAQ for known weirdness.

Bugs with WSL are reported to developers at https://github.com/microsoft/WSL

Kubespray (Ansible)

Video Tutorials

Create a new container:

The Dockerignore file contains names of files and folders that should not be in container images (because they are generated every time), such as:

The Dockerfile in each tutorial module defines the various base images from the Azure MCR.

Docker Enterprise Components

What was previously “Docker Engine” (and Docker’s 30% pentration into the Fortune 500) was purchased Nov, 2019 by Mirantis (the cloud consulting company with OpenStack roots). So it is now the Mirantis Container Runtime.

Docker’s “Universal Control Plane” is now Mirantis Kubenetes Engine (MKE), which provides RBAC & LDAP for centralized cluster management.

Docker’s “Trusted Registry” is now the Mirantis Secure Registry running MKE, hosting containers as a Linux server. It performs security scanning of image files.

To install MCR on Windows Server 2019, in PowerShell:

Docker Edge (at Tech Preview)

TODO: Use brew to install Docker Desktop Edge, in Technical Preview as of this writing.

bash-windows-docker

Sean Dearnaley provides pointers. It now supports Kubernetes, offers VPN-friendly networking, provides an updated Docker daemon, and many new features.

VHD size adjustment

WSL 2 stores Linux files inside of a VHD (Virtual Hard Disk) using the ext4 file system. VHD has an initial max size of 256GB. If your distro grows beyond that you will see errors stating that you’ve run out of disk space. To expand VHD size:

Terminate all WSL instances:

Find your distro installation package name ‘PackageFamilyName’.

In a powershell prompt (where ‘distro’ is your distribution name) construct:

Locate the VHD file fullpath used by your WSL 2 installation, this will be your ‘pathToVHD’:

Resize your WSL 2 VHD:

Open a command prompt Window with admin privileges and run the following commands:

Select vdisk file=”pathToVHD

expand vdisk maximum=”sizeInMegaBytes

Launch your WSL distro.

Make WSL is aware that it can expand its file system’s size by running these commands in your WSL distro:

Copy the name of this entry, which will look like: /dev/sdXX (with the X representing any other character), making sure to use the value you copied earlier.

You may need to use:

Akash Network

All of the above is getting ready for preparing your machine to generate revenue as provider clusters used by others on the Akash.cloud network. Leases of Akash resources are deployed via Kubernetes pods.

The Praetor application from Akash builds an Akash Provider for small and medium sized environments.

On a Windows machine, Praetor runs after Kubespray (using RedHat Ansible) on an Ubuntu server within WSL2. References:

    https://github.com/kubernetes-sigs/kubespray

VIDEO: “Kube 65.1 ] Kubespray — Kubernetes cluster provisioning”

VIDEO: “Deploying kubernetes using Kubespray” by Remko Deenik illustrating Steps to build the provider’s Kubernetes control plane and worker nodes:

Как установить и использовать оболочку Linux Bash в Windows 10

Подсистема Windows для Linux (Windows Subsystem for Linux, WSL), впервые представленная в Windows 10 версии 1607, стала действительно стабильной функцией в Windows 10 (версия 1709). Теперь пользователи получают среду для тестирования Linux-приложений прямо внутри Windows, которая работает быстрее, чем в виртуальной машине.

Что нужно знать про оболочку Bash в Windows 10

Подсистема Windows для Linux (WSL)

Функция WSL на самом деле не является виртуальной машиной, контейнером или программным обеспечением Linux, скомпилированным для Windows. Windows 10 предлагает полноценную подсистему Windows 10, предназначенную для запуска программного обеспечения Linux. Подсистема основана на проекте Microsoft Astoria, который первоначально предназначался для запуска приложений Android в Windows.

WSL можно рассматривать как противоположность Wine. В то время как Wine позволяет вам запускать приложения Windows прямо в Linux, подсистема Windows для Linux позволяет запускать приложения Linux непосредственно в Windows.

При создании среды оболочки на базе Bash Ubuntu, Microsoft работала совместно с компанией Canonical. Оболочка работает поверх подсистемы и технически не является Linux. Linux является основным ядром операционной системы, которое недоступно в подсистеме. Вместо этого функция WSL позволяет запускать оболочку Bash и исполнять такие же бинарные файлы, которые работают в Ubuntu Linux. Многие сторонники открытого программного обеспечения считает, что операционную систем Linux правильно называть именно “GNU/Linux”, потому что на ядре Linux работает много программного обеспечения GNU. Оболочка Bash, которую вы получаете в Windows 10, как раз содержит утилиты GNU и другое программное обеспечение.

Хотя эта функция изначально называлась “Ubuntu Bash в Windows”, она также позволяет запускать Zsh и другие оболочки командной строки. Сейчас поддерживаются и другие дистрибутивы Linux. Вы можете выбрать openSUSE Leap или SUSE Enterprise Server вместо Ubuntu, поддержка Fedora скоро будет реализована.

При использовании оболочки имеются некоторые ограничения. По умолчанию фоновое серверное ПО и графические приложения Linux не поддерживаются. Кроме того, в данной среде работают не все приложения командной строки, потому что функция не идеальна.

Как установить Bash в Windows 10

Данная функция не работает в 32-разрядной версии Windows 10, поэтому убедитесь, что вы используете 64-разрядную версию.

Если вы используете 64-битную версию Windows, то для начала работы перейдите в Панель управления > Программы и компоненты > Включение и отключение компонентов Windows. Отметьте галочкой пункт Подсистема Windows для Linux и нажмите кнопку ОК.

Подсистема Windows для Linux

Затем нажмите “Перезагрузить сейчас”, чтобы перезапустить компьютер и применить изменения. Функция не будет работать до перезагрузки.

Примечание: начиная с Windows 10 (версия 1709), чтобы использовать эту функцию вам больше не нужно включать режим разработчика в приложении Параметры. Вам просто нужно включить подсистему в окне “Компоненты Windows”.

После перезагрузки ПК откройте Магазин Microsoft и выполните поисковый запрос “Linux”. Откроется список доступных для установки приложений.

Магазин Microsoft

Примечание: начиная с Windows 10 (версия 1709), вы больше не сможете устанавливать Ubuntu, выполнив команду bash. Вместо этого вам нужно установить Ubuntu или другой дистрибутив Linux из Магазина Microsoft.

Итак, вы увидите список всех дистрибутивов Linux, доступных в Магазине Microsoft. Начиная с Windows 10 (версия 1709), в магазине предлагаются Ubuntu, openSUSE Leap, openSUSE Enterprise, Debian Linux, Arch Linux и Kali Linux.

Чтобы установить конкретный дистрибутив, выберите его и нажмите кнопку “Получить” или “Установить”. В результате запуститься обычная установка, как и в случае с другими приложениями из Магазина Microsoft.

Установить Ubuntu через Магазин Microsoft

Если вы не знаете, какую среду Linux установить, мы рекомендуем Ubuntu. Этот популярный дистрибутив Linux был ранее единственным доступным вариантом, но теперь доступны другие системы Linux для различных нужд пользователей.

Вы также можете установить несколько дистрибутивов Linux, и каждый из них получит свои собственные уникальные ярлыки. Вы даже можете запускать несколько разных дистрибутивов Linux одновременно в разных окнах.

Как использовать оболочку Bash и устанавливать программное обеспечение Linux

После успешной установки вы получаете полноценную командную оболочку Bash на основе Ubuntu или другого выбранного дистрибутива Linux.

Поскольку в системах Linux используются одинаковые бинарные файлы, вы можете использовать команды Ubuntu apt или apt-get, чтобы установить программное обеспечение из репозитория Ubuntu. Просто используйте любую команду, которую вы обычно используете в этом дистрибутиве Linux. У вас будет доступ ко всему программному обеспечению командной строки Linux там, хотя некоторые приложения могут работать не идеально.

Чтобы открыть установленную среду Linux, просто откройте меню Пуск и выполните поиск любого дистрибутива, который вы установили. Например, если вы установили Ubuntu, запустите ярлык Ubuntu.

запустите ярлык Ubuntu

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

При первом запуске среды Linux вам будет предложено ввести имя пользователя и пароль UNIX. Они не должны совпадать с вашим именем пользователя и паролем Windows, и будут использоваться в среде Linux.

При первом запуске среды Linux

Например, если вы введете “comss” и “qwerty” в качестве своих учетных данных, ваше имя пользователя в среде Linux будет “comss”, а пароль, который вы используете в среде Linux, будет “qwerty”, независимо от имени пользователя и пароля Windows.

Вы можете запустить установленную среду Linux с помощью команды wsl. Если у вас установлено несколько дистрибутивов Linux, вы можете выбрать среду Linux по умолчанию, которую будет запускаться этой командой.

Если у вас установлен Ubuntu, вы также можете запустить команду ubuntu для ее запуска. Для OpenSUSE Leap 42 используйте opensuse-42. Для SUSE Linux Enterprise Server 12 используйте sles-12. Эти команды перечислены на странице каждого дистрибутива Linux в Магазине Microsoft.

Кроме того, вы можете запустить стандартную среду Linux, выполнив команду bash, но Microsoft заявляет, что данный метод устаревает. Это означает, что команда bash может перестать функционировать в будущем.

Если у вас есть опыт использования оболочки Bash в Linux, MacOS или на других платформах, вы будете чувствовать себя уверенно.

В Ubuntu нужно использовать префикс команд sudo чтобы запускать их с правами root. Пользователь “root” на платформах UNIX имеет полный доступ к системе, аналогично “Администратору” в Windows. Файловая система Windows расположена по пути в /mnt/c в среде оболочки Bash.

В WSL можно использовать привычные команды терминала Linux. Если вы привыкли к стандартной командной строке Windows с ее командами DOS, вот несколько основных команд, общих для Bash и Windows:

  • Изменить директорию: cd в Bash, cd или chdir в DOS
  • Показать содержимое директории: ls в Bash, dir в DOS
  • Переместить или переименовать файл: mv в Bash, move и rename в DOS
  • Копировать файл: cp а Bash, copy в DOS
  • Удалить файл: rm в Bash, del или erase в DOS
  • Создать директорию: mkdir in Bash, mkdir в DOS
  • Использовать текстовые редактор: vi или nano в Bash, edit в DOS

Важно помнить, что, в отличие от Windows, оболочка Bash и имитирующая ее Linux среда чувствительны к регистру. Другими словами, файл с названием “File.txt” отличается от файла с названием “file.txt”.

Ubuntu

Для установки и обновления программного обеспечения среды Ubuntu нужно будет воспользоваться командой apt. Обязательно прикрепите эти команды к sudo, что заставляет их запускаться от пользователя root. Ниже представлены базовые команды apt-get, которые вам нужно знать:

  • Загрузить обновленную информацию о доступных пакетах: sudo apt update
  • Установить пакет приложения: sudo apt install packagename (замените packagename на название пакета)
  • Удалить пакет приложения: sudo apt remove packagename (замените packagename на название пакета)
  • Выполнить поиск доступных пакетов: sudo apt search word (замените word на ключевое слово в названии или описании пакета)
  • Загрузить и установить новейшие версии установленных пакетов: sudo apt upgrade

После того, как вы загрузили и установили приложение, вы можете ввести его имя в оболочку и нажать Enter для его запуска.

Примечание: Программное обеспечение, которое вы устанавливаете в оболочке Bash, ограничено оболочкой Bash. Вы можете получить доступ к этим программам из командной строки, PowerShell или из другого места в Windows, но только если вы запустите команду bash -c.

Дополнительно: установка родного шрифта Ubuntu

Если вы хотите получить более точный опыт использования Ubuntu в Windows 10, то можете использовать следующую инструкцию, чтобы установить родные шрифты Ubuntu в терминал.

Чтобы установить шрифт, сначала загрузите семейство шрифтов Ubuntu с веб-сайта Ubuntu. Откройте загруженный .zip-файл и найдите файл UbuntuMono-R.ttf. Это шрифт Ubuntu с фиксированный шириной, который используется только в терминале. Это единственный шрифт, который вам нужно установить.

Установка шрифта UbuntuMono-R

Дважды щелкните файл UbuntuMono-R.ttf, и вы увидите предварительный просмотр шрифта. Нажмите “Установить”, чтобы установить шрифт в систему.

Чтобы моноширинный шрифт Ubuntu стал доступен в консоли, вам нужно добавить параметр в реестр Windows.

Запустите редактор реестра, используя сочетание Windows + R , введя запрос regedit и нажав Enter.

Перейдите по следующему пути:

Ubuntu Mono

Щелкните правой кнопкой мыши в правой панели и выберите Создать > Строковый параметр . Назовите новое значение 000. Дважды щелкните на строке “000”, которую вы создали, а затем введите Ubuntu Mono в качестве значения.

Ubuntu Mono

Затем запустите окно Ubuntu, щелкните правой кнопкой мыши строку заголовка и выберите команду “Свойства”. Перейдите на вкладку “Шрифт” и выберите “Ubuntu Mono” в списке шрифта.

Using Bash in Windows

I have pretty much always been using windows. Most of my software development history is ASP.Net, with occasional forays into Java, Node.JS, and others. Even when I was developing in Java or Node, and even though the software I wrote would live in a completely Linux based ecosystem, my laptop always had Windows on it.

That being said, I have had continual exposure to the multitude of flavors of Linux. From desktop Ubuntu, to Centos, to DSL, LFS, RHEL, you name it. What I have never done, however, is install Linux on my laptop. For some reason Linux always seemed to me something that is disposable. If you need Linux to compile something, run your app, or host the church website, just kick up a VM on AWS and SSH into it.

This brings me to this topic — bash. Bash has many quirks and intricacies, but once you get used to it, going back to cmd just seems sad (and I’m not going to get into a PowerShell discussion, thank you). Wouldn’t it be great if we could use a bash shell in windows?

And mind you when I say “bash”, I am really referring to bash and coreutils.

There are a number of ways to get a bash kind of environment working in windows, so today I’m going to look at a few options that have appeared over the years.

Problem

At this point one might ask what is so hard about just using a bash shell in windows? After all we’re not talking about running Linux programs in windows (see Cygwin for that), we just want a shell. Can’t one just recompile awk and sed and everything to work on windows?

The simple answer is probably no, you can’t just recompile for Windows. The shell (specifically bash) is a core component for any Linux operating system. Furthermore, Windows and Linux paths are quite different. If there wasn’t some translation done between the formats, bash would be pretty useless on Windows. There are other differences too like the way bash expands wildcards, the way bash invokes executables, and the fact that some Windows and Linux tools have the same executable name, but work quite differently (e.g. sort or find).

Though there are many difficulties in getting a Linux based shell working, let alone CoreUtils, there have been a number of more or less successful attempts.

Cygwin

As far as I know Cygwin was the first attempt at getting a Linux-like environment working on Windows. It works by cross compiling Linux programs for windows, and includes a number of Libraries to reconcile the differences between the Windows operating system and Linux (like forking and threads).

Cygwin is quite comprehensive and sometimes feels like a Linux distro complete with package manager, X11 support and POSIX compliance. In many cases you can compile programs written for Linux without modification. But as the documentation is sure to point out, it’s still windows and the core workings of the operating system remain the same.

One can use Cygwin with it’s bash shell for general use in Windows, but I get the impression that this is not really the idea behind Cygwin. Furthermore Cygwin is pretty technical to install, and will take a good while unless you have low latency to the server you download from.

Though Cygwin is perhaps a bit much if you just want to use Bash inside Windows, MSYS comes to the rescue!

(For more information on Cygwin head over to the Cygwin home page.)

MSYS stands for “Minimal System.” and comes as part of MinGW — the minimalist GNU development environment for Windows. What they did was rip Bash and CoreUtils out of Cygwin and make it available as MSYS: a general purpose shell for Windows.

MSYS has kind of been abandoned as far as I can tell and has been superseded by MSYS2.

(MSYS and MinGw can be found on the MinGw website.)

MSYS2

MSYS2 is a rewrite of MSYS and aims to be Bash and a set of tools supporting the MinGW-w64 development toolchain (which is different from MinGw, if you were wondering).

MSYS2 aims to have better Windows interoperability, and also has a package manager of sorts.

(More info can be found on the MSYS2 website.)

Git for Windows

If you have Git installed on windows, you have probably already noticed that you have “Git Bash.” This Bash is the shell taken from MSYS2 and provided for use with Git related stuff. Git for windows also installs parts of MinGw. If you install the Git for Windows SDK, it will install a MinGw tool chain as well.

(Note: Bash and MinGw-w64 are needed to build Git on Windows, but I’m not sure whether Bash is needed to use git. I’m guessing Git internally uses Bash for something. Hooks or something I guess.)

Personally I find Git for Windows is a Bash shell on Windows that works really well. I’ve developed software projects that have tons of bash scripts and I rarely have problems running the same scripts on Windows and Linux. I’ve made it my default shell in VS Code and much prefer it to using CMD, even though the paths work differently.

I also set the option in the installer to make all the tools available in PATH. It warns that it might break windows scripts but I haven’t had any problems thus far.

How to run .sh on Windows Command Prompt?

Here the screen grab, enter image description here

11 Answers 11

Install GIT. During installation of GIT, add GIT Bash to windows context menu by selecting its option. After installation right click in your folder select GIT Bash Here (see attached pic) and use your sh command like for example:

enter image description here

Faisal Mq's user avatar

The error message indicates that you have not installed bash , or it is not in your PATH .

The top Google hit is http://win-bash.sourceforge.net/ but you also need to understand that most Bash scripts expect a Unix-like environment; so just installing Bash is probably unlikely to allow you to run a script you found on the net, unless it was specifically designed for this particular usage scenario. The usual solution to that is https://www.cygwin.com/ but there are many possible alternatives, depending on what exactly it is that you want to accomplish.

If Windows is not central to your usage scenario, installing a free OS (perhaps virtualized) might be the simplest way forward.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *