- Running bash scripts on windows
- Установка cygwin.
- Run Bash Scripts on Windows 10 Via Git Bash To Launch Linux GUI App
- How To Run Bash Scripts on Windows 10 Via Git Bash
- How to run .sh or Shell Script file in Windows 10
- How to run .sh or Shell Script file in Windows 10
- 1] Execute Shell Script file using WSL
- 2] Execute Shell Script using Ubuntu on Windows 10
- Related Posts
- Windows Subsystem for Linux has no installed distributions
- Failed to Fork error with Ubuntu on Windows 10
- WslRegisterDistribution failed with error 0x8007019e and 0x8000000d – WSL
- [email protected]
- Primary Sidebar
- Running Bash scripts on Windows
- Git for Windows
- Update PATHEXT
- GnuWin32
- MinGW
- Alias open
- Alias find
- Alternatives
- Standalone shells
- Bash on Windows: практические опыты по скрещиванию ежей и ужей
- Кейс номер один
- Путь первый — обращение к WMIC
- Путь второй — использование Scripting.FileSystemObject
- Кейс номер два
- Резюме
Running bash scripts on windows
Запустить bash скрипт из windows также просто как если бы вы использовали linux, необходимо всего лишь установить cygwin. Все используемые мной bash скрипты для администрирования железа прекрасно работаю под cygwin-ом.
Cygwin — бесплатный эмулятор командной строки Unix для Windows, используется для переноса программного обеспечения из UNIX в Windows, запуска скрипов bash, sh и т.п.
Установка cygwin.
1. Заходим на сайт программы — cygwin.com и закачиваем утилиту для установки setup.exe
2. Запускаем скачанную утилиту setup.exe и жмем далее.
3. Выбираем установку из интернета, жмем далее.
4. Выбираем папку для установки (по умолчанию C:\cygwin), жмем далее.
5. Выбираем папку для загрузки установочных файлов (по умолчанию C:\cygwin), жмем далее.
6. Выбираем тип соединения — прямое (Direct Connect) и жмем далее.
7. Выбераем сайт, с которого будут загружаться установочные файлы (я выбрал ftp://cygwin.uib.no), жмем далее.
8. Переходим к выбору устанавливаемых пакетов. Этот этап является наиболее важным, от него зависит работа запускаемых вами скриптов. Я при первой установке не выбрал пакет inetutils (в него входит утилита telnet), из-за чего написанный мной скрипт, использующий telnet, не работал. Тщательно изучите список предлагаемых пакетов и выберите необходимые вам. Я устанавливал из категории Net пакеты inetutils, openssh, openssl, ping, iperf, tftp, proftpd, а из раздела Utils пакеты utils-linux, mc, bzip2, ipcalc.
9. Отмечаем создать ярлык на рабочем столе и в меню пуск, нажимаем готово .
10. Запускаем ярлык Cygwin Terminal и работаем.
P.S. Для того, чтобы запустить bash скрипт, необходимо дать скрипту нужные права, используя команду:
namescript — название вашего скрипта вместе с расширением.
Вот и все. Теперь можно запускать bash скрипты из windows.
1″ :pagination=»pagination» :callback=»loadData» :options=»paginationOptions»>
Run Bash Scripts on Windows 10 Via Git Bash To Launch Linux GUI App
Git Bash Offers Integrity Options With Windows 10 Bash Making it Easy to Work on Both Windows & unix System. In old days, we used Git Bash with MinGW. Indeed, we have 5-7 years old guides on them. This Guide Will Help To Run Bash Scripts on Windows 10 Via Git Bash Almost Like The Way We Use Bash on Mac. We actually can run or update Mac GUI app from MacOS X bash. In the same way, we can launch Notepad or Nano from Windows Git Bash! This is a standalone shell, like PowerShell, Windows 10 Bash will be unaffected following this guide. Installing git on Windows Bash and installing git on windows in this way is different. There will not be any conflict. The environment variables are separate.
Then where is the integration? Git Bash and Windows Ubuntu Bash (wsl) are like two separate machines! We can actually execute command from each another. The output of the below command :
will be different on Git Bash and Windows Ubuntu Bash (wsl). Both of them can perform separate SSH. You can SSH from Git Bash to Windows Ubuntu Bash (wsl). It is not big deal, more about Linux server management. Unless your computer is server and port 22 is open to whole earth, slightly loose security setup will allow you to SSH.
You asked about where is the integration. SSH to localhost is integration. You’ll find lot of peoples trying to SSH to Windows Ubuntu Bash and failing. They forgot to set root’s password. After setting root password, thing will become somewhat like Mac! root by default not enabled in OS X. Apple’s software engineering part is beautiful. Microsoft’s just ugly.
What is the reason to do so much? Git Bash is allowed by package to open shell anywhere on Windows 10. You need not to fight with registry files, good looking window with True Type fonts.
How To Run Bash Scripts on Windows 10 Via Git Bash
First install Git Bash Windows GUI application :
How to run .sh or Shell Script file in Windows 10
Shell Scripts or .SH files are like batch files of Windows which can be executed in Linux or Unix. It is possible to run .sh or Shell Script file in Windows 10 using Windows Subsystem for Linux. In this post, we will show you how to run a Shell Script file in Windows 10.
How to run .sh or Shell Script file in Windows 10
Bash is a Unix shell and command language which can run Shell Script files. You do not need to install Ubuntu or any other Linux Distros unless your scripts need the support of the real Linux kernel. We will share both the methods.
- Execute Shell Script file using WSL
- Execute Shell Script using Ubuntu on Windows 10
1] Execute Shell Script file using WSL
Install WSL or Windows Subsystem for Linux
Go to Settings > Update & Security > For Developers. Check the Developer Mode radio button. And search for “Windows Features”, choose “Turn Windows features on or off”.
Scroll to find WSL, check the box, and then install it. Once done, one has to reboot to finish installing the requested changes. Press Restart now. BASH will be available in the Command Prompt and PowerShell.
Execute Shell Script Files
- Open Command Prompt and navigate to the folder where the script file is available.
- Type Bash script-filename.sh and hit the enter key.
- It will execute the script, and depending on the file, you should see an output.
On a Linux platform, you usually use SH, but here you need to use BASH. That said, BASH in Windows has its limitations, so if you want to execute in a Linux environment, you need to install Ubuntu or anything similar.
2] Execute Shell Script using Ubuntu on Windows 10
Make sure you have Ubuntu or any other Linux distros installed. Ubuntu will mount or make all your Windows directories available under /mnt. So the C drive is available at /mnt/C. So if the desktop will be available at /mnt/c/users/ /desktop.
Now follow these steps
- Type Bash in run prompt, and it will launch the distro prompt.
- Navigate to the folder using “cd” command to the folder where the scripts are available.
- Type “sh script.sh” and hit enter.
It will execute the script, and if they have a dependency on any of core Linux features.
Since Linux is now available in Windows, you need not use any third party applications like Cygwin. WSL should be enough for most of the scenarios to help you run a shell script in Windows 10.
Date: July 15, 2019 Tags: WSL
Related Posts
Windows Subsystem for Linux has no installed distributions
Failed to Fork error with Ubuntu on Windows 10
WslRegisterDistribution failed with error 0x8007019e and 0x8000000d – WSL
[email protected]
Ashish is a veteran Windows, and Xbox user who excels in writing tips, tricks, and features on it to improve your day to day experience with your devices.
Primary Sidebar
report this ad
Running Bash scripts on Windows
Apr 20, 2016 · 5 min read
The following setup allows one to run Bash scripts from Windows’ command prompt. It also augments it with common Unix commands like cp , rm and mv , which is useful if these are ingrained into muscle memory.
Note that this setup affects the command prompt (AKA cmd.exe ). A l though Windows 10 includes a full-fledged Ubuntu Linux Bash Shell, that shell – like PowerShell – is separate from the command prompt. Therefore, the following instructions still apply to Windows 10, as well as to earlier Windows versions. (For a brief list of standalone Bash shells for Windows, see the discussion at the end.)
Bash scripts (with an extension of .sh ) are a Unix invention, and should not be confused with batch files (with an extension of .bat ), which are a Windows invention. However, we could say that our goal is to help Windows run Bash scripts as if they were batch files.
Git for Windows
Install Git for Windows. When asked whether to install additional Unix utilities, choose Use Git and optional Unix tools from the Windows Command Prompt:
(The lighter Use Git from the Windows Command Prompt option can also be chosen, but then one must install MSYS manually.)
We can now open a command prompt window and run a Bash script as follows:
If the script accepts parameters, we just provide them at the end:
Git for Windows also extends the command prompt with common Unix commands like cp , rm and mv :
Git Bash, a standalone shell, is installed as well. It can be run as a separate program, or in the command prompt. To do the latter, just type bash ; to return to the standard command prompt, type exit . A .bash_profile file can be used to store settings between sessions. To edit this file, start Git Bash and type:
(Feel free to substitute vi for notepad if familiar with the former.) Below is an example file that configures the history size:
Configuring Bash settings is not covered here — that is a topic in its own right. Note that Git Bash typically stores the .bash_profile file at C:\Users\user\.bash_profile .
Update PATHEXT
With further refinements, we can trim the initial “ sh ” from the script invocation in the command prompt. First, associate .sh files with sh.exe . To do this, create a blank script.sh file (with Notepad, for example) and right-click on it. Choose Open with from the context menu. Click More apps and navigate to C:\Program Files\Git\bin\sh.exe . Enable Always use this app to open .sh files and click OK.
Next, update the value of the PATHEXT environmental variable. To access the variable, go to Control Panel → System → Advanced → Environment Variables. The value is a list of file extensions separated by ; , for example:
Add ;.SH to the end:
We can now run .sh files directly from the command prompt, like so:
We can also run a .sh file by clicking on it. However, note that the .sh extension is required to identify the file as a Bash script. Windows does not parse the #!/bin/sh shebang line; to execute an extensionless script, use sh (e.g., sh script ).
GnuWin32
For even more Unix utilities, install G nuW in32. Ensure that its utilities are globally available by appending the location of G nuW in32’s executables (its bin/ directory) to the PATH environment variable. The value is a list of file paths separated by ; , for example:
Thus, if G nuW in32’s executables are located in C:\GnuWin32\bin , simply add ;C:\GnuWin32\bin to the end:
On Windows 10, the variable may be displayed as an editable list of directories. Add the directory to the bottom of the list.
We now have a host of tools at our command. For example, make builds a software project from a Makefile, while wget downloads a file from the Internet. Peruse G nuW in32’s package list to get a sense of the possibilities.
MinGW
For additional developer tools, augment the above setup with a complete installation of MinGW. Append its directory to PATH after the other directories.
We can now link ( ld ) and compile C programs ( gcc ) and C++ programs ( g++ ).
Alias open
Windows does not have the open command, and none of the packages above provide it. To alias open to Windows’ start command, navigate to MSYS’ bin/ directory ( C:\Program Files\Git\usr\bin or C:\msys\1.0\bin ) and create an open.bat file containing the following:
For Git Bash, we need to add a Bash alias to .bash_profile . Start Git Bash and type:
Then add the following line:
Alias find
Windows’ own find utility shadows the Unix find command. To create an alias for the latter, make a copy of find.exe , find2.exe , in the same folder (typically C:\Program Files\Git\usr\bin ). The Unix command can now be accessed as find2 .
Alternatively, switch to Git Bash for the duration of the command:
Alternatives
The above instructions assume that MSYS is installed along with Git for Windows. However, it is also possible to install MSYS manually. If this applies, then run the MSYS installer and append MSYS’ bin/ directory to PATH after the other directories.
Standalone shells
Windows 10 includes its own Linux Bash Shell, based on Ubuntu. Note that this is a standalone shell, similar to PowerShell; Windows 10’s command prompt is unaffected and will still benefit from the instructions above. However, a standalone shell may provide built-in functionality that cannot be added to the command prompt (searchable history, for example).
Also note that if we install the Linux Bash Shell, then the bash command switches to that shell, not to Git Bash. However, we can still use the git bash command to change to Git Bash from the command prompt.
Another comprehensive standalone shell is provided by the Cygwin project, which can be used on older Windows versions. MSYS and MinGW also provide standalone shells. Git Bash, the shell provided by Git for Windows, is in fact an extension of these.
Bash on Windows: практические опыты по скрещиванию ежей и ужей
В прилетевшем обновлении Windows 10 Creators Update появилась интереснейшая возможность — запускать виндовые программы в этом их линуксе. Официальные примеры меня категорически не устроили — евангелисты Microsoft предложили мне рисовать корову в PowerShell и запускать Notepad из bash. Чё, правда? Это всё до чего вы додумались?
Как человек страстно ждавший возможность запуска exe-файлов внутри WSL, я хочу поделиться опытом правильного использования новой фичи.
Bash on Windows я использую для всякой мелкой механизации — выкачать, распарсить, проанализировать. Взять 10-20 гигов логов и поколдовать над ними в поисках чего нибудь этакого. Взять 200 гигов исходных данных, сделать ВЖУХ и пульнуть пару мегов результатов в базу сайта. Вобщем, обычная бытовуха, как у всех. Разве нет?
Кейс номер один
Вот то ради чего именно я ждал возможность запуска exe-файлов на WSL.
Имеется некоторое количество веб-сайтов для разных программ, требуется проверить что все ссылки «download» ведут на актуальные версии.
Пропустив этап поиска ссылок и скачивания файлов перейдём к извлечению нужной информации.
Делаем это двумя путями.
Путь первый — обращение к WMIC
В CMD вызов данной информации выглядит вот так:
/VALUE — что бы получить всю возможную информацию
В bash это выглядит вот так
слэшей много и все нужные
Но мне то нужно не просто на экран вывести, а получить и обработать.
Поэтому, в PHP это выглядит вот так:
/mnt/c/Windows/System32/cmd.exe — полный путь, что бы наверняка
$b — результат многострочный, поэтому получаем его в виде массива (в $a попадает лишь последняя строчка)
$ini — формат результата совместим с ini-файлом, грех этим не воспользоваться — превращаем полученный массив $b в текст для последующего преобразования с помощью parse_ini_string().
Путь второй — использование Scripting.FileSystemObject
Данной решение я нашёл здесь и немножко допилил.
В исходном варианте был вызов короткого списка с результатами, что меня не устроило
Я заменил эту строчку на цикл извлекающий ВСЕ возможные свойства файла
формат вывода сделан совместимым с ini-файлом.
PHP код, вызывающий bat-файл, получился вот такой
Почти так же как как в случае с WMI, только приходится перекодировать результат в юникод. ( CP866 — всплакнул )
Склеиваем полученные результаты в единый текст и парсим
Делаем разбиение на секции (второй параметр — true) и во избежании проблем включаем — INI_SCANNER_RAW
ВЖУХ и получаем массив всех возможных свойств файла с которым удобно работать.
Array
(
[WMIC] => Array
(
[AccessMask] => 1179817
[Archive] => TRUE
[Caption] => c:\windows\system32\cmd.exe
[Compressed] => FALSE
[CompressionMethod] =>
[CreationClassName] => CIM_LogicalFile
[CreationDate] => 20170318235750.921718+180
[CSCreationClassName] => Win32_ComputerSystem
[CSName] =>
[Description] => c:\windows\system32\cmd.exe
[Drive] => c:
[EightDotThreeFileName] => c:\windows\system32\cmd.exe
[Encrypted] => FALSE
[EncryptionMethod] =>
[Extension] => exe
[FileName] => cmd
[FileSize] => 271872
[FileType] => Application
[FSCreationClassName] => Win32_FileSystem
[FSName] => NTFS
[Hidden] => FALSE
[InstallDate] => 20170318235750.921718+180
[InUseCount] =>
[LastAccessed] => 20170318235750.921718+180
[LastModified] => 20170318235750.921718+180
[Manufacturer] => Microsoft Corporation
[Name] => c:\windows\system32\cmd.exe
[Path] => \windows\system32\
[Readable] => TRUE
[Status] => OK
[System] => FALSE
[Version] => 10.0.15063.0
[Writeable] => TRUE
)
[FileSystemObject] => Array
(
[Имя] => cmd.exe
[Размер] => 265 КБ
[Тип элемента] => Приложение
[Дата изменения] => 18.03.2017 23:57
[Дата создания] => 18.03.2017 23:57
[Дата доступа] => 18.03.2017 23:57
[Атрибуты] => A
[Автономность] =>
[Доступность] => Доступен автономно
[Распознанный тип] => Приложение
[Владелец] => TrustedInstaller
[Вид] => Программа
[Дата съемки] =>
[Исполнители] =>
[Альбом] =>
[Год] =>
[Жанр] =>
[Дирижер] =>
[Теги] =>
[Оценка] => Без оценки
[Авторы] =>
[Название] =>
[Тема] =>
[Категории] =>
[Комментарии] =>
[Авторские права] => c Microsoft Corporation. All rights reserved.
[№] =>
[Продолжительность] =>
[Скорость потока] =>
[С защитой] =>
[Камера, модель] =>
[Размеры] =>
[Камера, изготовитель] =>
[Организация] => Microsoft Corporation
[Описание файла] => Windows Command Processor
[Ключевые слова образцов] =>
[Имя программы] =>
[Длительность] =>
[В сети] =>
[Повторяется] =>
[Место] =>
[Адреса необязательных участников] =>
[Необязательные участники] =>
[Адрес организатора] =>
[Имя организатора] =>
[Время оповещения] =>
[Адреса обязательных участников] =>
[Обязательные участники] =>
[Ресурсы] =>
[Состояние собрания] =>
[Свободно/Занято] =>
[Общий размер] => 227 ГБ
[Учетная запись] =>
)
)
К чему был весь этот стрёмнокод? А вот к чему.
Как я уже упомянул ранее, на сайте майкрософта поведали, что теперь мы можем рисовать коров в PowerShell и запускать notepad.exe из баша.
А в обсуждении перевода этого майкрософтовского текста люди выясняют насколько там честный линукс и можно ли на него взгромоздить Докера.
Люди, вы не туда смотрите! Я в bash выполнил PHP-скрипт который через exec() запустил bat-файл в котором JScript создал ActiveXObject.
It’s Kind Of Magic!
А ещё я могу из CMD сделать вот так:
Кейс номер два
Обновление Windows 10 Creators Update я накатил 6 числа, а на прошлой недели был отвлечён от новой игрушки бухгалтерией. Бухгалтерия запросила оригиналы первички.
Эврика, подумал я и поставил консольную печаталку
Лезем в bash и просто запускаем программу
Результат — из принтера ползут листочки:
(данный скриншот — последующая имитация на виртуальном принтере, но на реальном HP тоже сработало)
В результате имеем:
- программа проявила интерактивность (триалка запросила нажать кнопочку)
- из башевского окошка полезла по своим виндовым путям
- взяла оттуда файлы с русскими названиями
- вызвала офисный редактор через COM-объекты
- отправила результат на принтер
То есть можно не только писать простейшие скриптики, но и использовать сложные программы.
Резюме
Я ещё не до конца осознал что ещё с этим можно делать, но эта штука может гораздо больше чем просто беседа с коровами и запуск LAMP.
Надо просто самому себе разрешить вырваться из дихотомиии «либо Linux, либо Windows» и начать скрещивать ежей и ужей в самых невероятных пропорциях и последовательностях.