Is there a way to run Bash scripts on Windows? [closed]
Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
I have bought and I use Windows 7 Ultimate, and I like to use it to develop applications. One of the down sides (as with every OS) is that I can not run Bash scripts. Is there a way to run Bash scripts on Windows by installing some software? It is ok if it does not work 100%, but as long as the most common functionality is available it should be great.
@stormy — these are console emulators and do not provide a shell. These can be used to run CMD, PowerShell or even a bash shell, if you have one installed.
8 Answers 8
Install Cygwin, which includes Bash among many other GNU and Unix utilities (without whom its unlikely that bash will be very useful anyway).
Another option is MinGW’s MSYS which includes bash and a smaller set of the more important utilities such as awk (you may also want to check the competing fork — Mingw-w64). Personally I would have preferred Cygwin because it includes such heavy lifting tools as Perl and Python which I find I cannot live without, while MSYS skimps on these and assumes you are going to install them yourself.
Updated: If anyone is interested in this answer and is running MS-Windows 10, please note that MS-Windows 10 has a «Windows Subsystem For Linux» feature which — once enabled — allows you to install a user-mode image of Ubuntu and then run Bash on that. This provides 100% compatibility with Ubuntu for debugging and running Bash scripts, but this setup is completely standalone from Windows and you cannot use Bash scripts to interact with Windows features (such as processes and APIs) except for limited access to files through the DrvFS feature.
Not deprecated, it’s just one of the features that you don’t get if you buy the cheaper Windows «Small edition». It’s also not available in the Home Edition, IIRC.
@MuhammadFaizanKhan — The Git port to Windows, as well as a few other «command-line oriented» applications (Github Desktop as a notable example) also come with a Windows port of Bash. These, more often then not, are MinGW ports (i.e. compiled using MinGW and MSYS for Posix compatibility). Specifically, if you look at your Git for Windows installation, you’d see the mingw32 directory that contains basically MSYS. So Git for Windows is MinGW that includes Git (its optional in the MSYS installer) with a «nicer» installer: superuser.com/a/1362301/10942
Best Option I could find is Git Windows Just install it and then right click on and click «Git Bash Here» this will open a bash window
This will open a bash window like this:
and the linux commands work.
I’ve tried ‘sh’ , ‘vi’ , ‘ssh’ , ‘curl’ ,etc. commands
I already had github desktop installed (and thus git), but I hid the context menu items, so I just clicked the windows Start button and typed Bash and pressed enter to open «Git Bash» (which is really MinGW).
If you’re looking for something a little more native, you can use getGnuWin32 to install all of the Unix command line tools that have been ported. That plus winBash gives you most of a working Unix environment. Add console2 for a better terminal emulator and you almost can’t tell you’re on Windows!
Cygwin is a better toolkit overall, but I have found myself running into surprise problems because of the divide between it and Windows. None of these solutions are as good as a native Linux system though.
You may want to look into using virtualbox to create a linux VM with your distro of choice. Set it up to share a folder with the host os, and you can use a true linux development environment, and share with windows. Just watch out for those EOL markers, they get ya every time.
Does anyone know of a successor to the win-bash project? It is no longer actively developed and stuck on bash v 1.14 (bash proper, as of this post, is v 4.4)
@Bjartr The Microsoft folks have added a feature to allow a native version of bash to run on windows 7
@SpencerRathbun That will only run on Windows 10, I happen to be on Windows 7. I’m also not sure how it plays with mixing linux and windows executables and paths so it may not be any better (from my perspective) than cygwin bash.
Best option? Windows 10. Native Bash support!
No, not best options. You just run linux that way, not bash IN windows — you cannot launch Windows executables from that bash (unless you workaround it with cbwin . but that’s already too much fuss for just a workaround).
‘Best’ option is probably a matter of taste. So maybe you’re right. However, it does enable me to run any (well .. most) bash scripts on my windows PC.
You can run virtual all bash scripts — as long as they do not try to interact with the host OS (Windows). WSL bash is a lightweight virtualization subsystem that can execute the original ELF binaries (ie Ubuntu) — but you cannot escape it!
You can always install Cygwin to run a Unix shell under Windows. I used Cygwin extensively with Window XP.
The Cygwin site explains what has been ported and how to install it. If all you want is a shell then the basic Cygwin install should be enough.
After installing git-extentions (http://gitextensions.github.io/) you can run .sh file from the command prompt. (No ./script.sh required, just run it like a bat/cmd file) Or you can run them in a «full» bash environment by using the MinGW Git bash shell.
I am not a great fan of Cygwin (yes I am sure it’s really powerful), so running bash scripts on windows without having to install it perfect for me.
I do not know what is git-extensions but its description says it is a graphical user interface for git. How would you run shell scripts from this tool? Perhaps you mean to run them with msys bash that it includes?
Just to confirm — git-extensions does include a copy of bash and it sets it in the path. I tried bash from a powershell instance, failed, installed git-extensions and retried and it worked for me.
In order to run natively, you will likely need to use Cygwin (which I cannot live without when using Windows). So right off the bat, +1 for Cygwin. Anything else would be uncivilized.
HOWEVER, that being said, I have recently begun using a combination of utilities to easily PORT Bash scripts to Windows so that my anti-Linux coworkers can easily run complex tasks that are better handled by GNU utilities.
I can usually port a Bash script to Batch in a very short time by opening the original script in one pane and writing a Batch file in the other pane. The tools that I use are as follows:
I prefer UnxUtils to GnuWin32 because of the fact that [someone please correct me if I’m wrong] GnuWin utils normally have to be installed, whereas UnxUtils are standalone binaries that just work out-of-the-box.
However, the CoreUtils do not include some familiar *NIX utilities such as cURL, which is also available for Windows (curl.haxx.se/download.html).
I create a folder for the projects, and always SET PATH=. in the .bat file so that no other commands other than the basic CMD shell commands are referenced (as well as the particular UnxUtils required in the project folder for the Batch script to function as expected).
Then I copy the needed CoreUtils .exe files into the project folder and reference them in the .bat file such as «.\curl.exe -s google.com», etc.
The Bat2Exe program is where the magic happens. Once your Batch file is complete and has been tested successfully, launch Bat2Exe.exe, and specify the path to the project folder. Bat2Exe will then create a Windows binary containing all of the files in that specific folder, and will use the first .bat that it comes across to use as the main executable. You can even include a .ico file to use as the icon for the final .exe file that is generated.
I have tried a few of these type of programs, and many of the generated binaries get flagged as malware, but the Bat2Exe version that I referenced works perfectly and the generated .exe files scan completely clean.
The resulting executable can be run interactively by double-clicking, or run from the command line with parameters, etc., just like a regular Batch file, except you will be able to utilize the functionality of many of the tools that you will normally use in Bash.
I realize this is getting quite long, but if I may digress a bit, I have also written a Batch script that I call PortaBashy that my coworkers can launch from a network share that contains a portable Cygwin installation. It then sets the %PATH% variable to the normal *NIX format (/usr/bin:/usr/sbin:/bin:/sbin), etc. and can either launch into the Bash shell itself or launch the more-powerful and pretty MinTTY terminal emulator.
There are always numerous ways to accomplish what you are trying to set out to do; it’s just a matter of combining the right tools for the job, and many times it boils down to personal preference.
Как в Windows 10 запускать SH-скрипты без подсистемы Bash
Большинству пользователей так или иначе приходилось сталкиваться со скриптами – мини-программами, используемыми обычно для чисто утилитарных целей. Наиболее распространены пакетные файлы CMD и BAT, однако иногда попадаются и другие типы скриптов, например, SH – сценарии, используемые прикладными программами в Bash. Несмотря на то, что предназначаются такие скрипты для Linux, благодаря интеграции подсистемы Bash они запросто могут быть выполнены и в Windows 10. Впрочем, если вы без подготовки попробуете запустить в «десятке» пакетный файл SH, то у системы не получится его обработать.
Чтобы иметь возможность запускать в среде Windows SH-сценарии, вам нужно ставить подсистему Linux. Но можно пойти и другим путем, установив альтернативные интерпретаторы, например, Git Bash или Cygwin. Они позволяют компилировать и запускать Unix и Linux-сценарии в Windows, причем как в 64-разрядной, так и в 32-разрядной версии системы.
Git Bash
Приложение Git Bash доступно для скачивания с сайта разработчика git-scm.com/downloads. Скачав версию для Windows вашей разрядности, установите программу, проигнорировав многочисленные настройки в окне мастера (менять их нет смысла). После запуска приложения вы увидите окно командной строки, очень похожей на окно стандартной консоли CMD, только с другим приглашением ввода.
Теперь, чтобы запустить SH-скрипт, перетащите его в окно консоли и нажмите ввод. Вот и всё, командный файл будет исполнен.
А еще вы можете открыть консоль Git Bash в любом каталоге, выбрав в контекстном меню Проводника, куда интерпретатор интегрируется при установке, опцию «Git Bash Here». В этом случае скрипты запускаются командой sn name, где name – имя скрипта.
Cygwin
Процедура установки приложения Cygwin, доступного для скачивания по ссылке www.cygwin.com, несколько отличается. В окне мастера-установщика вам нужно будет выбрать загрузку файлов из интернета, затем указать сервер (подойдет любой), место установки (по умолчанию корень диска C) и пакеты установки. Здесь всё можно оставить по умолчанию либо выбрать Full в выпадающем меню View.
Подобно Git Bash, Cygwin представляет собой командную строку, из которой и запускаются SH-скрипты. Да, перетаскивание в ней тоже работает.
Наконец, попробовать запустить SH-скрипт можно в обычной командной строке Windows 10, удалив в Блокноте первую строку #!/bin/bash и изменив расширение файла на BAT или CMD. Однако подобный скрипт отработает только в том случае, если содержащийся в нём код будет понятен интерпретатору CMD.