Как запустить скрипт start sh в windows

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

Шелл скрипты или .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.

Содержание:

  • 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

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

На чтение 6 мин. Просмотров 511 Опубликовано 26.04.2021

Файлы сценариев оболочки Bash написаны на языке сценариев bash для Linux. Он содержит команды, которые обычно можно запускать из командной строки. Эти файлы можно вызвать в Терминале для выполнения и открыть двойным щелчком. Однако Windows не знает, что такое файл SH и как его выполнить. Если вы ищете способ запустить файл SH в Windows, эта статья предоставит вам все возможные методы.

Содержание

  1. Что такое файлы SH?
  2. Метод 1: использование Cygwin для выполнения файлов SH
  3. Метод 2: Использование подсистемы Windows для функции Linux в Windows 10
  4. Шаг 1: Включение Подсистема Windows для Linux
  5. Шаг 2. Установка дистрибутива Linux для Windows
  6. Шаг 3. Инициализация только что установленного дистрибутива и выполнение файла SH
  7. Метод 3. Использование командной строки Git для выполнения Файлы SH
  8. Метод 4: Перевести файл сценария в пакетный файл

Что такое файлы SH?

Файлы SH (также известные как файлы сценариев) – это сценарии, которые используются приложениями Bash. Для написания инструкций в этих файлах используется язык Bash. Разработчики программ в основном используют эти файлы. Поскольку они содержат команды для выполнения программ, они действительно важны. Однако эти файлы предназначены для Linux, поэтому для их выполнения в Windows потребуется некоторое программное обеспечение или среда, которые мы предоставим в методах этой статьи.

Для получения дополнительной информации о файлах SH вы можете прочитать нашу статью здесь. Переходим к методам выполнения файлов SH в Windows.

Метод 1: использование Cygwin для выполнения файлов SH

Cygwin – это среда интерфейса командной строки с открытым исходным кодом, аналогичная Unix. Он позволяет компилировать приложения Unix или Linux и запускать их в операционной системе Windows из интерфейса, подобного Linux. Используя Cygwin, мы можем легко запускать файлы SH без каких-либо проблем.

  1. Перейдите на официальный сайт Cygwin , чтобы загрузить 32-битный или 64-битный файл установки: Cygwin
  2. Откройте загруженный установочный файл и следите за процессом загрузки и установки Cygwin. В процессе установки есть разные варианты, поэтому выберите те, которые вам больше нравятся.
  3. После установки откройте Cygwin64 Terminal , дважды щелкнув ярлык на рабочем столе .
  4. Теперь используйте следующую команду, чтобы изменить каталог, в котором существует файл:
     cd C: Users/ Имя пользователя/Рабочий стол 

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

     sh appuals.sh 

Метод 2: Использование подсистемы Windows для функции Linux в Windows 10

Подсистема Windows для Linux (также известная как WSL) – это функция, которая позволяет пользователям запускать командные строки Linux на компьютере с установленной операционной системой Windows 10. Эта функция была впервые добавлена ​​в Windows 10 в 2016 году. Так же, как в Linux есть программное обеспечение Wine для запуска программного обеспечения Windows, теперь в Windows есть WSL для запуска программного обеспечения Linux.. Однако для включения и работы с этой функцией потребуется много шагов, поэтому мы разделили этот метод на три основных шага, и они перечислены ниже:

Шаг 1: Включение Подсистема Windows для Linux

  1. Удерживайте клавишу Windows и нажмите R , чтобы открыть Выполнить , затем введите appwiz.cpl и Enter .
  2. Нажмите Включить или отключить функции Windows слева.
  3. Прокрутите вниз, установите флажок Подсистема Windows для Linux и нажмите ОК . для установки.
  4. После этого переходите к следующему шагу.

Шаг 2. Установка дистрибутива Linux для Windows

Есть три различных способа установить дистрибутив для Windows. Однако иногда один из методов не работает для конкретного пользователя, поэтому мы собираемся предоставить все три метода ниже:

  1. Hold Windows и нажмите R , чтобы открыть Выполнить , введите ‘ ms-windows-store: без кавычек и Введите .
  2. Найдите Ubuntu . Нажмите на тот, который показан ниже, и загрузите его:
  3. второй метод – использовать следующую команду Power shell для загрузки дистрибутива Linux:
     Invoke-WebRequest -Uri https://aka.ms/wsl-ubuntu-1604 -  OutFile Ubuntu.appx -UseBasicParsing 

  4. третий метод для загрузки дистрибутива используется следующая команда curl :
     curl.exe -L -o ubuntu-1604.appx https://aka.ms/wsl-ubuntu  -1604 

    Примечание . Если номер вашей сборки Windows 10 меньше 1706, то вам необходимо вручную загрузить curl и перейти в каталог, в котором находится curl.exe . Однако, если ваш номер сборки Windows 10 – 1706 или новее, то curl включен по умолчанию, и вам необходимо запустить cmd от имени администратора .

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

Шаг 3. Инициализация только что установленного дистрибутива и выполнение файла SH

  1. Большинство дистрибутивов, которые вы будете устанавливать, поставляются с пустым/минимальным каталогом пакетов. Поэтому вам необходимо обновить и обновить пакеты с помощью следующей команды:
     sudo apt update && sudo apt upgrade 

  2. Когда вы закончите работу с дистрибутивом, теперь вы можете сменить каталог на местоположение файла SH, используя следующие команды:
     cd/mnt 

    Это смонтирует ваш Windows диски . Теперь вы можете перейти в нужное место:

     cd c/Users/Username/Desktop/

    Примечание . Поскольку образец файла был на рабочем столе, поэтому мы изменили каталог на рабочий стол.

  3. Введите следующую команду, чтобы выполнить файл SH:
     sh appuals  .sh re>  

Метод 3. Использование командной строки Git для выполнения Файлы SH

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

  1. Перейдите по следующей ссылке, чтобы загрузить Git для вашей операционной системы. Система: Git
  2. Откройте загруженный установочный файл, чтобы установить Git . Пройдите процесс установки и проверьте, какие параметры вам нужны, а какие нет.
  3. Удерживая клавишу Windows , нажмите S , чтобы открыть функцию поиска , введите Git Bash и Enter .
  4. Измените каталог, в котором находится ваш файл, с помощью следующей команды:
     cd desktop 

    Примечание . Рабочий стол может быть именем папки, в которой находится ваш файл.

  5. Теперь введите команду выполнения SH:
      sh appuals.sh 

Метод 4: Перевести файл сценария в пакетный файл

Этот метод не рекомендуется для обычных пользователей, но для пользователей, которые очень хорошо знают команды файлов сценариев и bat. Вы можете просто изменить формат и расширение файла SH. Это требует навыков перевода файла сценария в пакетный файл, поэтому вам следует избегать использования этого метода, если вы не знаете, какой формат используют оба этих файла. Мы собираемся показать вам простые шаги, необходимые для изменения примера кода..

  1. Щелкните правой кнопкой мыши файл SH и выберите Открыть с помощью> Блокнота . .
  2. Удалите строку shebang из кода, как показано ниже:

    : комментарии будут иметь другой синтаксис « :: », чем в этом примере. .

  3. Щелкните Файл и выберите Сохранить в списке, чтобы сохранить изменения.
  4. Щелкните левой кнопкой мыши по SH-файлу и нажмите клавишу F2 , чтобы переименовать файл. Вы также можете щелкнуть правой кнопкой мыши по файлу и выбрать переименовать .

    Измените расширение с .sh на .bat и нажмите Да для внесения изменений.

  5. Удерживайте клавишу Windows и нажмите S , чтобы открыть функцию поиска . , затем введите cmd и Enter .
  6. Измените каталог на путь, по которому находится файл, используя cd :
     cd desktop 

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

  7. Теперь просто введите имя файла с расширением:
     appuals.bat 

    Однако вы заметите, что синтаксис, который работает в файлах сценария, не работает в пакетном файле. Как видите, комментарий игнорируется, и текст будет напечатан дважды без echo ‘on/off’ .

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

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

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

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

1]Выполнить файл сценария оболочки с помощью WSL

Установите WSL или подсистему Windows для Linux

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

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

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

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

Запустить файлы сценария оболочки из командной строки

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

2]Выполнить сценарий оболочки с помощью Ubuntu в Windows 10

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

Запускать файлы сценариев в Windows через Ubuntu

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

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

Он выполнит сценарий, и если они зависят от какой-либо из основных функций Linux.

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

Запустить файлы сценария оболочки из командной строки

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).

A .SH file is a simple text file that contains the commands and a little logic to it. There are several ways to run a .SH file. A .SH file is very similar to the batch file of the Windows operating system and can be run in the Linux-based operating system. It is also possible to run .SH file in Windows 10 using Windows Subsystem for Linux.

In this tutorial, we will show you how to run .SH files in Linux and Windows 10 systems.

In this section, we will show you how to run .SH file in Linux with examples.

Basic Steps to Run .SH Files

Before running .SH files, you will need to give execute permission on your file that you want to run. You can set execute permission with the following command:

chmod +x yourfilename.sh

Or

chmod 755 yourfilename.sh

Next, you can run your .SH file by running the following command:

sh yourfilename.sh

Or

bash yourfilename.sh

Or

./yourfilename.sh

Run .SH file as a root User

In some cases, you will need root access to install application or make system level modifications with .SH file. You can run .SH file as a root user by using the sudo command as shown below:

sudo bash yourfilename.sh

Type your user password and hit Enter to execute the .SH file.

You can also use su command to login with superuser and execute the .SH file.

First, switch the user to root with the following command:

su -

Next, run .SH file with the following command:

bash yourfilename.sh

Run .SH file with CHMOD Command

You can also use chmod command to run .SH file. First, set the execute permission on your file with the following command:

chmod +x yourfilename.sh

Next, run .SH file with the following command:

./yourfilename.sh

If your file is located at /opt directory then run the following command:

./opt/yourfilename.sh

Run .SH file with GUI Method

You can also run .SH file with Graphical user interface. To do so, first right click on the file that you want to run as shown below:

Next, click on the Properties. You should see the following screen:

Next, click on the permisssion tab and select Allow executing file as a program as shown below.

Next, double click on the file to execute the file.

Run .SH files in Windows 10

There are several ways to run .SH files in Windows 10 operating systems.

Run .SH file with WSL

WSL stands for “Windows Subsystem for Linux” is a compatibility layer for running Linux binary executables natively on Windows 10 and Windows Server 2019. It allows you to run native Linux command-line tools directly on Windows.

First, you will need to install WSL in your Windows 10 systems.

To do so, go to Settings > Update & Security > For Developers and check the Developer Mode radio button. Then, search for “Windows Features”, choose “Turn Windows features on or off”.

Next, scroll down, find WSL, check the box and install it. After installing WSL, you will need to restart your system to finish the installation.

Next, open the Command prompt, change the directory where yourfilename.sh is located and type bash yourfilename.sh to execute your file as shown below:

Run .SH File with Ubuntu on Windows 10

If you want to run .SH file in a Linux environment on Windows 10 then you will need to install Ubuntu or any other Linux distros on Windows 10.

You can install Ubuntu on Windows 10 by following the below steps.

First, go to Settings > Update & Security > For Developers and check the Developer Mode radio button. Then, search for “Windows Features”, choose “Turn Windows features on or off”.

Next, scroll down, find “Windows Subsystem for Linux (Beta)”, check the box and click Ok to install it. Once the installation has been finished, you will need to restart your system to finish installing the requested changes.

Next, open your Command prompt, type bash and hit Enter to install Ubuntu on Windows 10. Once the installation has been finished you should see the following screen:

Now, change the directory with cd command to the directory where yourfilename.sh is located and hit Enter to run the file as shown below:

Conclusion

In the above tutorial, we learned how to run .SH files in Linux and Windows 10 operating systems. I hope you have now enough knowledge to run .SH files in Linux and Windows 10.

Понравилась статья? Поделить с друзьями:
  • Как запустить рабочий стол на windows server 2019
  • Как запустить программу восстановления системы windows 10
  • Как запустить систему от имени администратора на windows 10
  • Как запустить процесс установки windows 10 с флешки
  • Как запустить скрипт ruby на windows