- Running bash script windows
- Установка cygwin.
- Как в Windows 10 запускать SH-скрипты без подсистемы Bash
- Git Bash
- Cygwin
- Windows shortcut to run a Git Bash script
- 4 Answers 4
- Single script to run in both Windows batch and Linux Bash?
- 11 Answers 11
- win-bash — A stand-alone bash for Windows
- What differs win-bash from cygwin-bash?
- How can I change the drive?
- Why did you port the very old bash 1.14.2 and not any newer version?
Running bash script 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»>
Как в 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.
Windows shortcut to run a Git Bash script
Assuming I have a test.sh script that runs a server and Git Bash installed, how do I create a Windows shortcut that I can double click to run tesh.sh in Git Bash in the foreground and allows me to see the output of the server?
4 Answers 4
Git bash is already a batch file with content similar to this :
If you want run (and leave running) a shell script in the context of the shell, specify it at the command line. The trick is that when the script file name is interpreted, it uses the Windows path, not the equivalent path in the sh/Git environment.
In other words, to run the file D:\temp\test.sh in the Git shell and leave it running, create this batch file :
On the other hand, if you want to run a script and get your shell back, you should :
- Open the shell as is
- Edit or create
/.profile )
Add this line :
/test.sh (ajdust the path if needed)
So with a .profile that looks like this :
And test.sh that looks like this :
You will get this prompt :
Other answers work, but there is a shorter solution, that fully answers the question, which was:
How to create a Windows shortcut that I can double click to run tesh.sh in Git Bash
The answer is: add the following command to the Target: field of the shortcut:
Where, -l is the short for —login .
To better understand what this command does, consult with official GNU docs about Invoking Bash:
- -l ( —login ): Make this shell act as if it had been directly invoked by login. When the shell is interactive, this is equivalent to starting a login shell with exec -l bash . When the shell is not interactive, the login shell startup files will be executed. exec bash -l or exec bash —login will replace the current shell with a Bash login shell.
Single script to run in both Windows batch and Linux Bash?
Is it possible to write a single script file which executes in both Windows (treated as .bat) and Linux (via Bash)?
I know the basic syntax of both, but didn’t figure out. It could probably exploit some Bash’s obscure syntax or some Windows batch processor glitch.
The command to execute may be just a single line to execute other script.
The motivation is to have just a single application boot command for both Windows and Linux.
Update: The need for system’s «native» shell script is that it needs to pick the right interpreter version, conform to certain well-known environment variables etc. Installing additional environments like CygWin is not preferable — I’d like to keep the concept «download & run».
The only other language to consider for Windows is Windows Scripting Host — WSH, which is preset by default since 98.
11 Answers 11
What I have done is use cmd’s label syntax as comment marker. The label character, a colon ( : ), is equivalent to true in most POSIXish shells. If you immediately follow the label character by another character which can’t be used in a GOTO , then commenting your cmd script should not affect your cmd code.
The hack is to put lines of code after the character sequence “ :; ”. If you’re writing mostly one-liner scripts or, as may be the case, can write one line of sh for many lines of cmd , the following might be fine. Don’t forget that any use of $? must be before your next colon : because : resets $? to 0.
A very contrived example of guarding $? :
Another idea for skipping over cmd code is to use heredocs so that sh treats the cmd code as an unused string and cmd interprets it. In this case, we make sure that our heredoc’s delimiter is both quoted (to stop sh from doing any sort of interpretation on its contents when running with sh ) and starts with : so that cmd skips over it like any other line starting with : .
Depending on your needs or coding style, interlacing cmd and sh code may or may not make sense. Using heredocs is one method to perform such interlacing. This could, however, be extended with the GOTO technique:
Universal comments, of course, can be done with the character sequence : # or :;# . The space or semicolon are necessary because sh considers # to be part of a command name if it is not the first character of an identifier. For example, you might want to write universal comments in the first lines of your file before using the GOTO method to split your code. Then you can inform your reader of why your script is written so oddly:
Thus, some ideas and ways to accomplish sh and cmd -compatible scripts without serious side effects as far as I know (and without having cmd output ‘#’ is not recognized as an internal or external command, operable program or batch file. ).
win-bash — A stand-alone bash for Windows
win-bash is a Windows port of the famous GNU bash (see GNU Bash homepage).
Unlike other bash ports for Windows (e.g. the cygwin bash ), the win-bash needs no special environment or DLLs. There is just one binary and that’s it.
win-bash is based on nt_bash which was an early bash port for Windows NT started by Mountain Math Software some years ago. As far as I know, the nt_bash port project stopped in alpha status and has never been finished.
The goal of the win-bash project is to finish the port to Windows and provide a fully-functional bash.exe binary for Windows NT and derived systems. win-bash can be used as an input shell, as well as an interpreter to run UN*X shell scripts.
- Further Information
- FAQ
- Installation
-
- Sourceforge Project Page ->http://sourceforge.net/projects/win-bash/
- Download ->https://sourceforge.net/projects/win-bash/files/shell-complete/latest/
- EGCS Development Toolchain for GNU-Mingw32 ->The MinGW Compiler and Tools
- GNU utilities for Win32 ->The unxutils project
- ViewCVS ->http://win-bash.cvs.sourceforge.net/viewvc/win-bash/win-bash/
-
What differs win-bash from cygwin-bash?
First of all, you should keep in mind that win-bash is based on a old version of bash (1.14.2) while cygwin -bash is more or less up to date.
One important difference is the handling of drives: cygwin uses its installation directory as root dir and links all drives in the pseudo subdir /cygdrive . win-bash uses a diffent method: drives are included in paths, like on windows (e.g. c:/Winnt/System32 ). The root directory / is mapped to the root directory of the current drive.
Examples:
- ls c:/winnt — shows the content of the directory c:/winnt
- cd c:/; ls /winnt — changes current drive to c: and shows the content of the directory c:/winnt
- cd d:/; ls /winnt — changes current drive to d: and shows the content of the directory d:/winnt
There are some other differences, most of them have been added to simplify the usage of existing un*x shell scripts:
- If a shell script starts with an interpreter specification like #!/path/interpreter , the interpreter is searched in the PATH environment instead of /path . E.g. a Perl script starting with #!/bin/perl will be started with perl.exe from the PATH environment variable.
- win-bash doesn’t use any dlls or registry keys
How can I change the drive?
Use the cd command. The drive letter is optional and can be added at the head of the directory followed by a colon. If the drive letter is given, the current drive is changed. The root directory / always points the the current drive’s root dir.
To change to the root directory on drive c: write:
Why did you port the very old bash 1.14.2 and not any newer version?
win-bash is based on nt_bash which was based on bash 1.14.2. The port was primary started to make un*x shell scripts run on windows. All tested scripts worked fine with this old version, so the primary goal of the project has been reached even with this old bash version.
The installation of win-bash is pretty simply: Just download shell.w32-ix86.zip, unpack it and copy the bash.exe file to a path which is listed in your PATH environment variable.
When using win-bash as the default shell for un*x shell scripts, you may which to copy bash.exe to sh.exe to make scripts starting with #!/bin/sh work.
Remember: This is only the shell binary — it has same builtin commands, but for must purposes you would need additional un*x tools like ls, sed etc. The unxutils project provides Windows ports of often used un*x tools.