Как запустить bash файл на windows

How can I run .sh on Windows 7 Command Prompt? I always get this error when I try to run this line in it, app/build/build.sh error, 'app' is not recognized... or, bash app/build/build.sh erro...

How can I run .sh on Windows 7 Command Prompt? I always get this error when I try to run this line in it,

app/build/build.sh

error,

'app' is not recognized...

or,

bash app/build/build.sh

error,

'bash' is not recognized...

Any ideas what have I missed?

Here the screen grab,
enter image description here

asked Oct 23, 2014 at 6:59

Run's user avatar

1

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:

sh test.sh

enter image description here

answered May 27, 2016 at 8:15

Faisal Mq's user avatar

Faisal MqFaisal Mq

4,7764 gold badges34 silver badges39 bronze badges

4

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.

The second error message is due to the fact that Windows nominally accepts forward slash as a directory separator, but in this context, it is being interpreted as a switch separator. In other words, Windows parses your command line as app /build /build.sh (or, to paraphrase with Unix option conventions, app --build --build.sh). You could try appbuildbuild.sh but it is unlikely to work, because of the circumstances outlined above.

answered Oct 23, 2014 at 7:33

tripleee's user avatar

tripleeetripleee

170k31 gold badges261 silver badges305 bronze badges

1

The most common way to run a .sh file is using the sh command:

C:>sh my-script-test.sh 

other good option is installing CygWin

in Windows the home is located in:

C:cygwin64home[user]

for example i execute my my-script-test.sh file using the bash command as:

jorgesys@INT024P ~$ bash /home/[user]/my-script-test.sh 

answered Jun 9, 2015 at 23:09

Jorgesys's user avatar

JorgesysJorgesys

123k23 gold badges328 silver badges264 bronze badges

6

you can use also cmder

Cmder is a software package created out of pure frustration over the absence of nice console emulators on Windows. It is based on amazing software, and spiced up with the Monokai color scheme and a custom prompt layout, looking sexy from the start

Screenshot

cmder.net

answered Oct 18, 2016 at 17:05

vipmaa's user avatar

vipmaavipmaa

1,00216 silver badges24 bronze badges

1

On Windows 10 Anniversary Update, it’s even easier to run shell commands in/with bash on ubuntu on windows

I was trying to set my region for my x-wrt r7000 netgear router, I found the following worked for me, using bash on ubuntu on windows, you do have to enable subsystem found in windows features, and dev mode on

ssh admin@192.168.1.1 < /mnt/c/ccode-eu.sh

Martin Tournoij's user avatar

answered Aug 25, 2016 at 21:10

SignedAdam's user avatar

SignedAdamSignedAdam

711 silver badge1 bronze badge

1

Install the GitBash tool in the Windows OS. Set the below Path in the environment variables of System for the Git installation.

<Program Files in C:>Gitbin

<Program Files in C:>Gitusrbin

Type ‘sh‘ in cmd window to redirect into Bourne shell and run your commands in terminal.

answered Aug 21, 2020 at 19:36

TechRookie's user avatar

TechRookieTechRookie

1411 silver badge4 bronze badges

1

Personally I used this batch file, but it does require CygWin installed (64-bit as shown).
Just associate the file type .SH with this batchfile (ExecSH.BAT in my case) and you can double-click on the .SH and it runs.

@echo off
setlocal

if not exist "%~dpn1.sh" echo Script "%~dpn1.sh" not found & goto :eof

set _CYGBIN=C:cygwin64bin
if not exist "%_CYGBIN%" echo Couldn't find Cygwin at "%_CYGBIN%" & goto :eof

:: Resolve ___.sh to /cygdrive based *nix path and store in %_CYGSCRIPT%
for /f "delims=" %%A in ('%_CYGBIN%cygpath.exe "%~dpn1.sh"') do set _CYGSCRIPT=%%A
for /f "delims=" %%A in ('%_CYGBIN%cygpath.exe "%CD%"') do set _CYGPATH=%%A

:: Throw away temporary env vars and invoke script, passing any args that were passed to us
endlocal & %_CYGBIN%mintty.exe -e /bin/bash -l -c 'cd %_CYGPATH%;  %_CYGSCRIPT% %*'

Based on this original work.

answered Feb 21, 2017 at 12:23

Anonymouse's user avatar

AnonymouseAnonymouse

9379 silver badges20 bronze badges

I use Windows 10 Bash shell aka Linux Subsystem aka Ubuntu in Windows 10 as guided here

answered Apr 9, 2020 at 6:20

Nam G VU's user avatar

Nam G VUNam G VU

32.2k68 gold badges226 silver badges366 bronze badges

just install git and by «bash <name.sh>» run your .sh file.

answered Apr 3, 2021 at 8:51

Ali Ganjbakhsh's user avatar

Have you tried cding to the root directory where your .sh is located in order to execute it from there, instead of writing down a path to the file as you showed in your question?

Like so:

$ cd app/build
$ build.sh

answered May 28, 2021 at 6:59

D4V1D's user avatar

D4V1DD4V1D

5,7353 gold badges29 silver badges64 bronze badges

Шелл скрипты или .SH файлы похожи на командные файлы Windows, которые могут выполняться в Linux или Unix.

В Windows 10 можно запустить файл .sh или скрипт оболочки, используя подсистему Windows для Linux.

В этом руководстве мы покажем вам, как запустить файл скрипта оболочки в Windows 10.

Содержание

  1. Как запустить файл .sh или скрипт шелла в Windows 10
  2. 1] Выполнить файл скрипта оболочки, используя WSL
  3. 2] Выполнить скрипт оболочки, используя Ubuntu в Windows 10

Как запустить файл .sh или скрипт шелла в Windows 10

Bash – это оболочка и командный язык Unix, который может запускать файлы скрипты .sh.

Вам не нужно устанавливать Ubuntu или любые другие дистрибутивы Linux, если ваши скрипты не нуждаются в поддержке реального ядра Linux.

Мы поделимся обоими методами.

  • Выполнить файл скрипт оболочки, используя WSL
  • Выполнить скрипт оболочки с помощью Ubuntu в Windows 10

1] Выполнить файл скрипта оболочки, используя WSL

Установите WSL или Windows Subsystem для Linux

Перейдите в Настройки> Обновление и безопасность> Для разработчиков.

Проверьте переключатель режима разработчика.

Поищите «Функции Windows», выберите «Включить или отключить функции Windows».

Прокрутите, чтобы найти WSL, установите флажок и установите его.

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

Нажмите Перезагрузить сейчас.

BASH отныне будет доступен в командной строке и PowerShell.

Выполнить файлы скриптов оболочки

  • Откройте командную строку и перейдите в папку, где доступен файл скрипта
  • Введите Bash script-filename.sh и нажмите клавишу Enter.
  • Система выполнит скрипт, и в зависимости от файла вы должны увидеть вывод.

На платформе Linux вы обычно используете SH, но здесь вам нужно использовать BASH.

Тем не менее, BASH в Windows имеет свои ограничения, поэтому, если вы хотите выполнить их в среде Linux, вам нужно установить Ubuntu или что-то подобное.

2] Выполнить скрипт оболочки, используя Ubuntu в Windows 10

Убедитесь, что у вас установлена Ubuntu или любой другой дистрибутив Linux.

Ubuntu смонтирует или сделает все ваши каталоги Windows доступными в /mnt.

Таким образом, диск C доступен по адресу /mnt/C.

Таким образом рабочий стол будет доступен по адресу /mnt/c/users/<username>/desktop.

Теперь следуйте этим шагам

  • В командной строке введите Bash, и система запустит приглашение дистрибутива.
  • Перейдите в папку с помощью команды «cd» , где доступны скрипты.
  • Введите «sh script.sh» и нажмите Enter

Система выполнит скрипт

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

WSL должно быть достаточно для большинства скриптов, чтобы помочь вам запустить эти самые крипты оболочки в Windows 10.

How can I run .sh on Windows 7 Command Prompt? I always get this error when I try to run this line in it,

app/build/build.sh

error,

'app' is not recognized...

or,

bash app/build/build.sh

error,

'bash' is not recognized...

Any ideas what have I missed?

Here the screen grab,
enter image description here

asked Oct 23, 2014 at 6:59

Run's user avatar

1

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:

sh test.sh

enter image description here

answered May 27, 2016 at 8:15

Faisal Mq's user avatar

Faisal MqFaisal Mq

4,7764 gold badges34 silver badges39 bronze badges

4

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.

The second error message is due to the fact that Windows nominally accepts forward slash as a directory separator, but in this context, it is being interpreted as a switch separator. In other words, Windows parses your command line as app /build /build.sh (or, to paraphrase with Unix option conventions, app --build --build.sh). You could try appbuildbuild.sh but it is unlikely to work, because of the circumstances outlined above.

answered Oct 23, 2014 at 7:33

tripleee's user avatar

tripleeetripleee

170k31 gold badges261 silver badges305 bronze badges

1

The most common way to run a .sh file is using the sh command:

C:>sh my-script-test.sh 

other good option is installing CygWin

in Windows the home is located in:

C:cygwin64home[user]

for example i execute my my-script-test.sh file using the bash command as:

jorgesys@INT024P ~$ bash /home/[user]/my-script-test.sh 

answered Jun 9, 2015 at 23:09

Jorgesys's user avatar

JorgesysJorgesys

123k23 gold badges328 silver badges264 bronze badges

6

you can use also cmder

Cmder is a software package created out of pure frustration over the absence of nice console emulators on Windows. It is based on amazing software, and spiced up with the Monokai color scheme and a custom prompt layout, looking sexy from the start

Screenshot

cmder.net

answered Oct 18, 2016 at 17:05

vipmaa's user avatar

vipmaavipmaa

1,00216 silver badges24 bronze badges

1

On Windows 10 Anniversary Update, it’s even easier to run shell commands in/with bash on ubuntu on windows

I was trying to set my region for my x-wrt r7000 netgear router, I found the following worked for me, using bash on ubuntu on windows, you do have to enable subsystem found in windows features, and dev mode on

ssh admin@192.168.1.1 < /mnt/c/ccode-eu.sh

Martin Tournoij's user avatar

answered Aug 25, 2016 at 21:10

SignedAdam's user avatar

SignedAdamSignedAdam

711 silver badge1 bronze badge

1

Install the GitBash tool in the Windows OS. Set the below Path in the environment variables of System for the Git installation.

<Program Files in C:>Gitbin

<Program Files in C:>Gitusrbin

Type ‘sh‘ in cmd window to redirect into Bourne shell and run your commands in terminal.

answered Aug 21, 2020 at 19:36

TechRookie's user avatar

TechRookieTechRookie

1411 silver badge4 bronze badges

1

Personally I used this batch file, but it does require CygWin installed (64-bit as shown).
Just associate the file type .SH with this batchfile (ExecSH.BAT in my case) and you can double-click on the .SH and it runs.

@echo off
setlocal

if not exist "%~dpn1.sh" echo Script "%~dpn1.sh" not found & goto :eof

set _CYGBIN=C:cygwin64bin
if not exist "%_CYGBIN%" echo Couldn't find Cygwin at "%_CYGBIN%" & goto :eof

:: Resolve ___.sh to /cygdrive based *nix path and store in %_CYGSCRIPT%
for /f "delims=" %%A in ('%_CYGBIN%cygpath.exe "%~dpn1.sh"') do set _CYGSCRIPT=%%A
for /f "delims=" %%A in ('%_CYGBIN%cygpath.exe "%CD%"') do set _CYGPATH=%%A

:: Throw away temporary env vars and invoke script, passing any args that were passed to us
endlocal & %_CYGBIN%mintty.exe -e /bin/bash -l -c 'cd %_CYGPATH%;  %_CYGSCRIPT% %*'

Based on this original work.

answered Feb 21, 2017 at 12:23

Anonymouse's user avatar

AnonymouseAnonymouse

9379 silver badges20 bronze badges

I use Windows 10 Bash shell aka Linux Subsystem aka Ubuntu in Windows 10 as guided here

answered Apr 9, 2020 at 6:20

Nam G VU's user avatar

Nam G VUNam G VU

32.2k68 gold badges226 silver badges366 bronze badges

just install git and by «bash <name.sh>» run your .sh file.

answered Apr 3, 2021 at 8:51

Ali Ganjbakhsh's user avatar

Have you tried cding to the root directory where your .sh is located in order to execute it from there, instead of writing down a path to the file as you showed in your question?

Like so:

$ cd app/build
$ build.sh

answered May 28, 2021 at 6:59

D4V1D's user avatar

D4V1DD4V1D

5,7353 gold badges29 silver badges64 bronze badges

How can I run .sh on Windows 7 Command Prompt? I always get this error when I try to run this line in it,

app/build/build.sh

error,

'app' is not recognized...

or,

bash app/build/build.sh

error,

'bash' is not recognized...

Any ideas what have I missed?

Here the screen grab,
enter image description here

asked Oct 23, 2014 at 6:59

Run's user avatar

1

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:

sh test.sh

enter image description here

answered May 27, 2016 at 8:15

Faisal Mq's user avatar

Faisal MqFaisal Mq

4,7764 gold badges34 silver badges39 bronze badges

4

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.

The second error message is due to the fact that Windows nominally accepts forward slash as a directory separator, but in this context, it is being interpreted as a switch separator. In other words, Windows parses your command line as app /build /build.sh (or, to paraphrase with Unix option conventions, app --build --build.sh). You could try appbuildbuild.sh but it is unlikely to work, because of the circumstances outlined above.

answered Oct 23, 2014 at 7:33

tripleee's user avatar

tripleeetripleee

170k31 gold badges261 silver badges305 bronze badges

1

The most common way to run a .sh file is using the sh command:

C:>sh my-script-test.sh 

other good option is installing CygWin

in Windows the home is located in:

C:cygwin64home[user]

for example i execute my my-script-test.sh file using the bash command as:

jorgesys@INT024P ~$ bash /home/[user]/my-script-test.sh 

answered Jun 9, 2015 at 23:09

Jorgesys's user avatar

JorgesysJorgesys

123k23 gold badges328 silver badges264 bronze badges

6

you can use also cmder

Cmder is a software package created out of pure frustration over the absence of nice console emulators on Windows. It is based on amazing software, and spiced up with the Monokai color scheme and a custom prompt layout, looking sexy from the start

Screenshot

cmder.net

answered Oct 18, 2016 at 17:05

vipmaa's user avatar

vipmaavipmaa

1,00216 silver badges24 bronze badges

1

On Windows 10 Anniversary Update, it’s even easier to run shell commands in/with bash on ubuntu on windows

I was trying to set my region for my x-wrt r7000 netgear router, I found the following worked for me, using bash on ubuntu on windows, you do have to enable subsystem found in windows features, and dev mode on

ssh admin@192.168.1.1 < /mnt/c/ccode-eu.sh

Martin Tournoij's user avatar

answered Aug 25, 2016 at 21:10

SignedAdam's user avatar

SignedAdamSignedAdam

711 silver badge1 bronze badge

1

Install the GitBash tool in the Windows OS. Set the below Path in the environment variables of System for the Git installation.

<Program Files in C:>Gitbin

<Program Files in C:>Gitusrbin

Type ‘sh‘ in cmd window to redirect into Bourne shell and run your commands in terminal.

answered Aug 21, 2020 at 19:36

TechRookie's user avatar

TechRookieTechRookie

1411 silver badge4 bronze badges

1

Personally I used this batch file, but it does require CygWin installed (64-bit as shown).
Just associate the file type .SH with this batchfile (ExecSH.BAT in my case) and you can double-click on the .SH and it runs.

@echo off
setlocal

if not exist "%~dpn1.sh" echo Script "%~dpn1.sh" not found & goto :eof

set _CYGBIN=C:cygwin64bin
if not exist "%_CYGBIN%" echo Couldn't find Cygwin at "%_CYGBIN%" & goto :eof

:: Resolve ___.sh to /cygdrive based *nix path and store in %_CYGSCRIPT%
for /f "delims=" %%A in ('%_CYGBIN%cygpath.exe "%~dpn1.sh"') do set _CYGSCRIPT=%%A
for /f "delims=" %%A in ('%_CYGBIN%cygpath.exe "%CD%"') do set _CYGPATH=%%A

:: Throw away temporary env vars and invoke script, passing any args that were passed to us
endlocal & %_CYGBIN%mintty.exe -e /bin/bash -l -c 'cd %_CYGPATH%;  %_CYGSCRIPT% %*'

Based on this original work.

answered Feb 21, 2017 at 12:23

Anonymouse's user avatar

AnonymouseAnonymouse

9379 silver badges20 bronze badges

I use Windows 10 Bash shell aka Linux Subsystem aka Ubuntu in Windows 10 as guided here

answered Apr 9, 2020 at 6:20

Nam G VU's user avatar

Nam G VUNam G VU

32.2k68 gold badges226 silver badges366 bronze badges

just install git and by «bash <name.sh>» run your .sh file.

answered Apr 3, 2021 at 8:51

Ali Ganjbakhsh's user avatar

Have you tried cding to the root directory where your .sh is located in order to execute it from there, instead of writing down a path to the file as you showed in your question?

Like so:

$ cd app/build
$ build.sh

answered May 28, 2021 at 6:59

D4V1D's user avatar

D4V1DD4V1D

5,7353 gold badges29 silver badges64 bronze badges

When I am trying to execute a file(name.sh) in the command line by the command ./name.sh , I am getting the error that:

«.» is not recognized as an internal
or external command, operable or batch
file

please help me execute the .sh file

Broam's user avatar

Broam

3,98418 silver badges20 bronze badges

asked Mar 15, 2010 at 7:34

0

You’re on Windows CMD.EXE (from the error message). It uses a different syntax to execute commands. You’ll need to use sh name.sh, assuming that you’ve got Cygwin or similar installed.

To clarify, Windows does not have a built-in utility to support .sh files. To run such, you’ll need to install a third-party tool such as Cygwin.

Rich Homolka's user avatar

Rich Homolka

30.5k6 gold badges52 silver badges79 bronze badges

answered Mar 15, 2010 at 7:58

Roger Lipscombe's user avatar

Roger LipscombeRoger Lipscombe

2,1933 gold badges21 silver badges34 bronze badges

3

Best solution in my opinion:

  • Download and install .git for Windows

  • Right click desktop and say «git bash here»

  • Execute your script like in unix

  • Done!

Caution: Many commands won’t work on windows! But still, a lot of the basic stuff will work.

If you need that script regularly you may want to create a shortcut (on your desktop e.g.):

  • Create a Shortcut to mintty.exe on your desktop

  • Edit properties of the shortcut and change the target (keep the path):

  • C:Program FilesGitusrbinmintty.exe" -h always /bin/bash -l -e 'D:folderscript.sh'

answered Apr 9, 2017 at 18:58

Hannes Schneidermayer's user avatar

2

You are trying to run a Linux command at the Windows Command Prompt.

On Linux the forward slash is a path separater. On Windows the backslash is a path separator and the forward slash generally indicates an argument.

Therefore, Windows thinks you are trying to run a command called «.» and parsing it the argument «/name.sh». The correct convention would be «.name.sh». Additionally Windows will automatically search the current directory for your command so you could just type «name.sh».

The next problem you will face is that Windows does not know what a sh script is, again this is a Linux thing. You could solve this by installing Cygwin if you really want or need to run a sh script.

However, judging by one of your previous comments you could just as well rename the script to name.bat and delete the «#!/bin/sh» line. Now you have a Batch file which Windows should understand. You can read more about batch files here.

answered Mar 15, 2010 at 13:48

Martin Fido's user avatar

Martin FidoMartin Fido

3112 silver badges3 bronze badges

Alternatively you could turn to the dark side and install Linux. From the prompt:

sh runide.sh

or

sudo sh runide.sh

Your program will run and you will have a better system as well.

Gaff's user avatar

Gaff

18.3k15 gold badges56 silver badges68 bronze badges

answered Nov 18, 2010 at 15:46

steve's user avatar

stevesteve

1371 silver badge2 bronze badges

2

You’re trying to run your car on orange juice instead of gasoline. Windows shares similar commands stored in .bat or .cmd files with Unix/Linux/zOS Unix Subsystem/*ix shell scripts as these two families of operating systems share a common ancestor the DEC PDP-x machines.

If you want instant gratification, you will need to install an environment that provides a «sh.exe» program or «csh.exe» or «bash.exe» program (tsh.exe anyone?)

Alternatively, if you know Unix script commands, very well, and you know Windows .cmd and .bat file commands, very well, you can translate the .sh file into a .bat or .cmd file. Even so, you will often encounter more Unix-styled programs that have no equivalent under Windows—grep, sed, vi, emacs, etc. Thus, the call to install CygWin (no minimalist)—just to get the shell and Unix tools. Put it on a flash-drive, for these special occasions.

answered Aug 16, 2011 at 22:52

J.M.'s user avatar

J.M.J.M.

511 silver badge1 bronze badge

Someone said something about MS-DOS using / for commands and for paths. This is slightly misleading. Look at my example:

C:myfoofoo>cd../.. 
C:myfoofoo>cd....

Has no difference in effect. Yes, it is not true for all operations – the actual answer is simply No, or without Cygwin or SSHD you can’t.

I only know because I stupidly spent half a day trying to figure out what if then fi and eval, exec do with -Djava.something when called.

slhck's user avatar

slhck

219k68 gold badges591 silver badges578 bronze badges

answered May 28, 2012 at 23:19

grizzleybear123's user avatar

This is an old thread but for those running Windows 10. Just open windows features from the control panel ‘Turn Windows Features on or Off’

Choose the feature ‘Windows Subsystem for Linux’.
After installing, you have ‘Bash’ and you even can configure native Linux servers within bash.
And of course,
the sh command, within bash, works too.

answered May 1, 2018 at 16:06

Egbert's user avatar

I found a different and easy solution, called UnixUtil.

Download and unzip it to C: drive. Set the environment variable path to include C:UnixUtilsusrlocalwbin.

This is important. DO NOT set path to C:UnixUtilsbin

Canadian Luke's user avatar

answered May 13, 2014 at 22:05

prabhanjan deshpande's user avatar

For completeness I want to mention a new “Windows Subsystem for Linux” feature for Windows 10. The details are described in http://www.howtogeek.com/249966/how-to-install-and-use-the-linux-bash-shell-on-windows-10/

Note, that it requires activate the “Developer Mode” switch and
enable the “Windows Subsystem for Linux (Beta)” option.

For myself I found that Git for Windows installation (that I am using anyway) is sufficient.

answered Dec 27, 2016 at 10:39

Michael Freidgeim's user avatar

It’s possible that the problem is actually within the file name.sh — you are trying to use the . command but it is attempting to run a kind of shell (e.g., csh, I think) in which that’s not a valid command.

So: does name.sh start with the correct #!/bin/sh (if you are actually trying to run sh)?

answered Mar 15, 2010 at 7:55

Andrew Jaffe's user avatar

1

ok, there’s a LOT wrong with that — drop the #!/bin/sh, and change the extention to bat, and it might work with a few more fixes. Then you can just invoke it by its filename as well.

The syntax of a unix shell script, and a windows batch file arn’t too similar. cygwin, or a load of messing around with unxutils might make something that would work in both, but unless you’re ABSOLUTELY sure the environment is always the same, it isn’t worth the headache

answered Mar 15, 2010 at 13:46

Journeyman Geek's user avatar

Journeyman GeekJourneyman Geek

125k51 gold badges252 silver badges418 bronze badges

3

If you have a Linux box in your home (or work) and plugged to the same network, and this network is safe, this might do the trick:

  1. Make a folder share on Windows (pretty easy, but make sure the network is safe from intruders).
  2. Mount it in Linux with mount //WinMachine/Share LinuxFolder (IIRC, and requires Samba).
  3. Using something like PuTTY, log in remotely to that Linux box.
  4. Run your command in the mounted folder.

answered Aug 31, 2012 at 15:16

Camilo Martin's user avatar

Camilo MartinCamilo Martin

2,5544 gold badges30 silver badges41 bronze badges

To run the shell script from the windows.
First use the command : dos2unix
then you can use your normal command :
sh runide.sh

This will work out.

answered Nov 23, 2015 at 11:57

Sridhar GV's user avatar

2

Although the existing answers here were correct at the time, Windows 10 does now optionally include a modified version of Ubuntu running a full bash shell.

Once made executable, scripts can be run in the usual way from within bash, eg:

chmod +x myscript.sh
./myscript.sh

If you want to run a script directly from the Windows you could create a shortcut in the same directory and set the ‘Target’ to something like:

C:WindowsSystem32bash.exe -c "./myscript.sh"

If the path of your script is relative to the location of the shortcut (like the example above) ensure the ‘Start in’ field is also blank.

answered Aug 25, 2016 at 7:34

Molomby's user avatar

MolombyMolomby

1,7451 gold badge16 silver badges15 bronze badges

Bash (Bourne Again Shell) — это командная строка и графический пользовательский интерфейс, распространяемый со всеми дистрибутивами Linux. Использование Bash в Windows 10 было непростым процессом. Однако Windows 11 включает в себя обновленную подсистему Windows для Linux (WSL 2.0), которая позволяет устанавливать и использовать Bash проще, чем когда-либо.

Новая версия WSL запускает настоящее ядро ​​Linux внутри виртуальной машины. Это означает, что любой дистрибутив Linux, который вы запускаете под WSL, включает Bash.

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

Чтобы установить и запустить операционные системы Linux, включающие Bash, в вашей системе Windows 11, вам необходимо сначала установить WSL. В Windows 11 это простой процесс с использованием Windows Terminal. Не запускайте CMD (командную строку) — Windows Terminal — это другое приложение.

1. Нажмите кнопку «Пуск» и введите «терминал» в поле поиска. В панели терминала Windows выберите «Запуск от имени администратора».

Примечание. Если Windows Terminal не запускается, возможно, вам потребуется обновить его. Посетите Microsoft Store и установите последнюю версию Windows Terminal.

2. Введите следующую команду: wsl –install в командной строке и нажмите Enter. Эта единственная команда загрузит и установит последнюю версию подсистемы Windows для Linux. Загрузка составляет несколько сотен мегабайт, поэтому процесс установки может занять некоторое время.

3. По завершении вы должны увидеть сообщение: «Запрошенная операция выполнена успешно». Когда вы увидите это сообщение, перезагрузите систему, чтобы завершить установку WSL. Вы можете ввести shutdown / r / t 0 в терминале Windows, чтобы начать перезагрузку.

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

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

6. Вы можете установить другие дистрибутивы Linux, если хотите. Чтобы узнать, какие из них доступны для установки, снова откройте Windows Terminal (Powershell), введите wsl –list –online и нажмите Enter. Вы увидите такие варианты, как Opensuse, Debian и другие.

7. Вы можете установить любой из этих дистрибутивов, набрав wsl –install -d <<distr name>> в терминале Windows. Повторится тот же процесс, что и при предыдущей установке Ubuntu, и вам потребуется ввести имя пользователя и пароль для завершения установки.

Примечание. Вы также можете установить любой дистрибутив Linux в Windows из Магазина Microsoft.

Как запустить дистрибутив Linux и использовать Bash

Есть два метода, которые вы можете использовать для запуска вашего дистрибутива Linux. Если вы установили Ubuntu, вы можете выбрать меню «Пуск», ввести Ubuntu и выбрать приложение Ubuntu для его запуска.

Кроме того, вы можете запустить терминал Windows и просто ввести команду Ubuntu, чтобы запустить оболочку Linux Bash в среде Ubuntu.

Чтобы просмотреть список всех доступных команд Linux, которые вы можете использовать в Bash, введите help -d

Вы можете получить более подробную информацию об отдельных командах, набрав help и имя команды. Например, help printf возвращает сведения о команде и информацию о каждом параметре команды.

Некоторые из наиболее распространенных команд Bash, которые большинство людей используют при первом запуске, включают:

  • Интерактивный режим: ввод команд в интерфейс командной строки (терминал Windows).
  • Пакетный режим: запустите текстовый файл, содержащий все команды, которые вы хотите, чтобы Linux выполнял по порядку. Многие люди создают эти сценарии, используя синтаксис программирования.

Как запустить скрипт Bash в Windows

Чтобы запустить сценарий в Bash, просто создайте текстовый файл в своем любимом файловом редакторе, таком как Блокнот, и сохраните его в удобном для вас месте.

Уникальность сценария Bash заключается в том, что первая строка должна быть «#!». за которым следует путь вашего пути Linux bash. Чтобы увидеть, что это такое, запустите Ubuntu и введите bash в окно командной строки. Это обеспечит путь Bash.

Создайте новый текстовый файл и включите эту первую строку вверху. В случае с этим примером это будет:

#! /user/bin/bash

Следуйте этой строке с каждой последовательной командой, которую вы хотите запустить в Linux. В этом примере:

  • Строка 1: использует команду echo для отображения текста пользователю на экране.
  • Строка 2: объединяет эхо с командой даты, чтобы вернуть сегодняшнюю дату.
  • Строка 3: объединяет эхо с командой whoami, чтобы вернуть ваше имя пользователя.

Сохраните этот текстовый файл с расширением .sh. Запомните путь к этому файлу.

Затем откройте терминал Windows и используйте команду cd, чтобы перейти к пути, по которому вы сохранили сценарий Bash.

Чтобы запустить скрипт, введите bash <<script name>>.

Это очень простой пример, но он демонстрирует, как вы можете использовать такой файл для создания целых программ сценариев Bash. Даже операторы программирования, такие как операторы IF, доступны для включения возможностей принятия решений в ваш сценарий.

Сайт SS64 предоставляет обширный ресурс со всеми доступными командами Bash, которые вы можете использовать в терминале Bash или в сценариях Bash.


Download PC Repair Tool to quickly find & fix Windows errors automatically

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 11/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.

  1. Execute Shell Script file using WSL
  2. 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

  1. Open Command Prompt and navigate to the folder where the script file is available.
  2. Type Bash script-filename.sh and hit the enter key.
  3. It will execute the script, and depending on the file, you should see an output.

Run Shell script files from Command Prompt

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 11/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/<username>/desktop.

Run Script files in Windows via Ubuntu

Now follow these steps

  1. Type Bash in run prompt, and it will launch the distro prompt.
  2. Navigate to the folder using “cd” command to the folder where the scripts are available.
  3. Type “sh script.sh” and hit Enter.

It will execute the script, and if they have a dependency on any of the 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 11/10.

How do I create a .SH file?

The steps to create a shell script file are:

  • Create a file using a editor
  • Name script file with extension . sh
  • Start the script with #! /bin/sh
  • Write the desired code
  • Save the script file as ABC.sh
  • For executing the script type bash ABC.sh.

Can you run shell scripts in Windows?

Yes, now with Bash Shell in Windows 11 and Windows 10, you can now create and run Bash shell scripts and incorporate Bash commands into a Windows batch file or PowerShell script.

Ezoic

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. He has been a Microsoft MVP (2008-2010).

  1. Home
  2. OS
  3. Windows
  4. Как запустить bash скрипт из windows

Запустить bash скрипт из windows также просто как если бы вы использовали linux, необходимо всего лишь установить cygwin. Все используемые мной bash скрипты для администрирования железа прекрасно работаю под cygwin-ом.

 Cygwin — бесплатный эмулятор командной строки Unix для Windows, используется для переноса программного обеспечения из UNIX в Windows, запуска скрипов bash, sh и т.п.

Установка cygwin.

1. Заходим на сайт программы — cygwin.com и закачиваем утилиту для установки setup.exe

2. Запускаем скачанную утилиту setup.exe и жмем далее.

cygwin_install_1

3. Выбираем установку из интернета, жмем далее.

cygwin_install_2

4. Выбираем папку для установки (по умолчанию C:cygwin), жмем далее.

cygwin_install_3

5. Выбираем папку для загрузки установочных файлов (по умолчанию C:cygwin), жмем далее.

cygwin_install_4

6. Выбираем тип соединения — прямое (Direct Connect) и жмем далее.

cygwin_install_5

7. Выбераем сайт, с которого будут загружаться установочные файлы (я выбрал ftp://cygwin.uib.no), жмем далее.

cygwin_install_6

8. Переходим к выбору устанавливаемых пакетов. Этот этап является наиболее важным, от него зависит работа запускаемых вами скриптов. Я при первой установке не выбрал пакет inetutils (в него входит утилита telnet), из-за чего написанный мной скрипт, использующий telnet, не работал. Тщательно изучите список предлагаемых пакетов и выберите необходимые вам. Я устанавливал из категории Net пакеты inetutils, openssh, openssl, ping, iperf, tftp, proftpd, а из раздела Utils пакеты utils-linux, mc, bzip2, ipcalc.

cygwin_install_7

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

cygwin_install_8

10. Запускаем ярлык Cygwin Terminal и работаем.

P.S. Для того, чтобы запустить bash скрипт, необходимо дать скрипту нужные права, используя команду:

chmod 777 namescript

затем запустить:

./namescript

namescript — название вашего скрипта вместе с расширением.

Вот и все. Теперь можно запускать bash скрипты из windows.

Меня два раза спрашивали [члены Парламента]: «Скажите на милость, мистер Бэббидж, что случится, если вы введёте в машину неверные цифры? Cможем ли мы получить правильный ответ?» Я не могу себе даже представить, какая путаница в голове может привести к подобному вопросу. / Charles Babbage /

Содержание:

  • 1 Git Bash
  • 2 Cygwin

Большинству пользователей так или иначе приходилось сталкиваться со скриптами – мини-программами, используемыми обычно для чисто утилитарных целей. Наиболее распространены пакетные файлы 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, только с другим приглашением ввода.

Установка Git Bash

Теперь, чтобы запустить SH-скрипт, перетащите его в окно консоли и нажмите ввод. Вот и всё, командный файл будет исполнен.

Выполнение скрипта в Git Bash

zapusk-sh-skriptov-v-win-10-3

А еще вы можете открыть консоль Git Bash в любом каталоге, выбрав в контекстном меню Проводника, куда интерпретатор интегрируется при установке, опцию «Git Bash Here». В этом случае скрипты запускаются командой sn name, где name – имя скрипта.

Пункт Git Bash Here в контекстном меню проводника Windows

Cygwin

Процедура установки приложения Cygwin, доступного для скачивания по ссылке www.cygwin.com, несколько отличается. В окне мастера-установщика вам нужно будет выбрать загрузку файлов из интернета, затем указать сервер (подойдет любой), место установки (по умолчанию корень диска C) и пакеты установки. Здесь всё можно оставить по умолчанию либо выбрать Full в выпадающем меню View.

Установка Cygwin этап 1

Установка Cygwin этап 2

Подобно Git Bash, Cygwin представляет собой командную строку, из которой и запускаются SH-скрипты. Да, перетаскивание в ней тоже работает.

Запуск скрипта в Cygwin

Наконец, попробовать запустить SH-скрипт можно в обычной командной строке Windows 10, удалив в Блокноте первую строку #!/bin/bash и изменив расширение файла на BAT или CMD. Однако подобный скрипт отработает только в том случае, если содержащийся в нём код будет понятен интерпретатору CMD.

Редактирование скрипта в блокноте для запуска в командной строке Windows

Shell Scripts или .SH файлы похожи на командные файлы Windows, которые могут выполняться в Linux или Unix. В Windows 10 можно запустить файл .sh или Shell Script, используя подсистему Windows для Linux. В этом посте мы покажем вам, как запустить файл сценария оболочки в Windows 10.

Bash — это оболочка и командный язык Unix, который может запускать файлы Shell Script. Вам не нужно устанавливать Ubuntu или любые другие дистрибутивы Linux, если ваши сценарии не нуждаются в поддержке реального ядра Linux. Мы поделимся обоими методами.

  1. Выполнить файл сценария оболочки, используя WSL
  2. Выполнить сценарий оболочки с помощью Ubuntu в Windows 10

1] Выполнить файл сценария оболочки, используя WSL

Установите WSL или Windows Subsystem для Linux

Перейдите в Настройки → Обновление и безопасность → Для разработчиков. Проверьте переключатель режима разработчика. Ищите «Функции Windows», выберите «Включить или отключить функции Windows».

Прокрутите, чтобы найти WSL, установите флажок и установите его. После этого необходимо перезагрузить компьютер, чтобы завершить установку запрошенных изменений. Нажмите Перезагрузить сейчас. BASH будет доступен в командной строке и PowerShell.

Выполнить файлы сценариев оболочки

  • Откройте командную строку и перейдите в папку, где доступен файл сценария.
  • Введите Bash script-filename.sh и нажмите клавишу ввода.
  • Он выполнит скрипт, и в зависимости от файла вы должны увидеть вывод.

На платформе Linux вы обычно используете SH, но здесь вам нужно использовать BASH. Тем не менее, BASH в Windows имеет свои ограничения, поэтому, если вы хотите выполнить в среде Linux, вам нужно установить Ubuntu или что-то подобное.

2] Выполнить сценарий оболочки, используя Ubuntu в Windows 10

Убедитесь, что у вас установлен Ubuntu или любой другой дистрибутив Linux. Ubuntu смонтирует или сделает все ваши каталоги Windows доступными в /mnt. Таким образом, диск C доступен по адресу /mnt/C. Так что если рабочий стол будет доступен по адресу /mnt/c/users/<username>/desktop.

Теперь следуйте этим шагам

  1. В командной строке введите Bash, и он запустит приглашение distro.
  2. Перейдите в папку с помощью команды «cd» в папку, где доступны сценарии.
  3. Введите «sh script.sh» и нажмите ввод.
  4. Он выполнит сценарий, и если они зависят от каких-либо основных функций Linux.

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

Понравилась статья? Поделить с друзьями:
  • Как запустить bash скрипт на windows
  • Как запустить avertv на windows 10
  • Как запустить autoruns для windows 10
  • Как запустить autorun exe на windows 10
  • Как запустить autohotkey на windows 10