- Как запустить файл .sh или Shell Script в Windows 10
- 1] Выполнить файл сценария оболочки, используя WSL
- 2] Выполнить сценарий оболочки, используя Ubuntu в Windows 10
- How to Execute SH Files on Windows
- What are the SH Files?
- Method 1: Using Cygwin to Execute SH Files
- Method 2: Using the Windows Subsystem for Linux Feature in Windows 10
- Step 1: Enabling the Windows Subsystem for Linux
- Step 2: Installing a Linux Distro for the Windows
- Step 3: Initializing a Newly Installed Distro and Executing SH File
- Method 3: Using Git Command Line for Executing SH Files
- Method 4: Translate Script File into Batch File
- Как выполнить файл .sh в Windows?
Как запустить файл .sh или Shell Script в Windows 10
Shell Scripts или .SH файлы похожи на командные файлы Windows, которые могут выполняться в Linux или Unix. В Windows 10 можно запустить файл .sh или Shell Script, используя подсистему Windows для Linux. В этом посте мы покажем вам, как запустить файл сценария оболочки в Windows 10.
Bash — это оболочка и командный язык Unix, который может запускать файлы Shell Script. Вам не нужно устанавливать Ubuntu или любые другие дистрибутивы Linux, если ваши сценарии не нуждаются в поддержке реального ядра Linux. Мы поделимся обоими методами.
- Выполнить файл сценария оболочки, используя WSL
- Выполнить сценарий оболочки с помощью 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/ /desktop.
Теперь следуйте этим шагам
- В командной строке введите Bash, и он запустит приглашение distro.
- Перейдите в папку с помощью команды «cd» в папку, где доступны сценарии.
- Введите «sh script.sh» и нажмите ввод.
- Он выполнит сценарий, и если они зависят от каких-либо основных функций Linux.
Поскольку Linux теперь доступен в Windows, вам не нужно использовать какие-либо сторонние приложения, такие как Cygwin. WSL должно быть достаточно для большинства сценариев, чтобы помочь вам запустить сценарий оболочки в Windows 10.
How to Execute SH Files on Windows
Bash shell script files are written in bash scripting language for Linux. It contains commands that you can normally run on the command line. These files can be called in Terminal to execute and can be opened by double-clicking. However, Windows does not know what an SH file is and how to execute it. If you are looking for a way to execute SH file in Windows then this article will provide you with all possible methods.
Execute SH files on Windows
What are the SH Files?
SH files (also known as script files) are the scripts that the Bash application programs and use. Bash language is used to write the instructions in these files. Program developers mostly use these files. Since they contain the commands to execute programs, they are indeed important. However, these files are for Linux, so executing them on Windows will require some software or environment that we will provide in methods of this article.
For further information about SH files, you can check our article here. Moving on towards methods for executing SH files on Windows.
Method 1: Using Cygwin to Execute SH Files
Cygwin is an open source command line interface environment similar to Unix. It allows Unix or Linux applications to be compiled and run on a Windows operating system from within a Linux-like interface. By using Cygwin, we can easily execute SH files without any problems.
- Go to the Official Cygwin site to download the 32bit or 64bit setup file: Cygwin
Download site for Cygwin
- Open the downloaded setup file and follow the process of downloading and installing Cygwin. There are different options in the installation process so choose the ones you prefer.
- After installation, open Cygwin64 Terminal by double-clicking the shortcut on the desktop.
- Now use the following command to change directory to where the file exists:
This will change the directory to the desktop. Now type the following command to execute SH File:
Executing script file through Cygwin
Method 2: Using the Windows Subsystem for Linux Feature in Windows 10
The Windows Subsystem for Linux (aka WSL) is a feature that allows users to run Linux command lines on a computer with a Windows 10 operating system installed. This feature was first added to Windows 10 in 2016. Just like Linux has Wine software for running Windows software, now Windows has WSL for running Linux software. However, enabling and working through this feature will require many steps, which is why we divided this method into three major steps and they are listed as follow:
Step 1: Enabling the Windows Subsystem for Linux
- Hold Windows Key and Press R to open Run, then type appwiz.cpl and Enter.
Opening Programs and Features
- Click on the Turn Windows Features on or off on the left side.
Opening Turn Windows features on or off option
- Scroll down to the bottom and tick Windows Subsystem for Linux and click Ok to install.
Enabling Windows Subsystem for Linux
- Once this is done, move to the next step.
Step 2: Installing a Linux Distro for the Windows
There are three different ways to install a distro for Windows. However, sometimes one of the methods will not work for a specific user, so we are going to provide all three methods below:
- Hold Windows key and press R to open Run, type ‘ms-windows-store:‘ without the quotation marks and Enter.
Opening the Windows Store
- Search for Ubuntu. Click on the one that is shown below and download it:
Downloading Ubuntu from Windows Store
- The second method is to use the following Power shell command to download Linux distro:
Downloading distro through Power Shell
- The third method to download the distro is using the following curl command:
Downloading distro through curl command
Note: If your Windows 10 build number is less than 1706 then you need to download curl manually and change directory to that location where curl.exe is located. However, if your windows 10 build number is 1706 or later then curl is included by default and you need to run cmd as an administrator.
Once you download a distro, it will start the installation automatically and you need to just agree and provide the new username and password as shown below:
Step 3: Initializing a Newly Installed Distro and Executing SH File
- Most distros that you will install comes with empty/minimal package catalog. So you need to update and upgrade the packages by using the following command:
Updating and Upgrading packages
- Once you are done with the distro, now you can change directory to the SH file location by using the following commands:
This will mount your Windows drives. Now you can go to the location you want to:
Note: Since the sample file was on a desktop so we changed the directory to desktop.
Method 3: Using Git Command Line for Executing SH Files
Git is a free and open source distributed version control system tool available for all operating systems. By default, Git is installed on Linux and macOS computers as a command line option. However, you can also download it from the official site for all operating systems.
- Go to the following link to download Git for your Operating System: Git
Downloading Git for Windows
Note: Desktop can be the name of the folder where your file is located.
Method 4: Translate Script File into Batch File
This method is not recommended for average users, but for the users who know script and bat files commands very well. You can just change the format and extension of SH file. It does require the skill of translating the script file into a batch file, so you should avoid using this method unless you know what format both these files use. We are going to show you the simple steps required for the sample code changes.
- Right-click on your SH file and choose Open with > Notepad.
Opening SH file in Notepad
Remove the shebang line from the code as shown below: Removing the shebang line
Note: The comments will have a different syntax “::” than the one in this sample.
Change the extension from .sh to .bat and click Yes for the changes.
Note: Desktop can be the folder name that you are trying to access.
Now simply type the name of the file with extension: Opening batch file in cmd
However, you will notice that the syntax that works in script files are not working in a batch file. As you can see, the comment is being ignored and the text will be printed twice without echo ‘on/off’.
Как выполнить файл .sh в Windows?
Когда я пытаюсь выполнить файл (name.sh) в командной строке с помощью команды ./name.sh, я получаю сообщение об ошибке:
«» не распознается как внутренняя или внешняя команда, рабочий или пакетный файл
пожалуйста, помогите мне выполнить файл .sh
Вы находитесь на Windows CMD.EXE (из сообщения об ошибке). Он использует другой синтаксис для выполнения команд. Вам нужно будет использовать sh name.sh , предполагая, что у вас установлен Cygwin или аналогичный.
Для пояснения, в Windows нет встроенной утилиты для поддержки файлов .sh. Чтобы запустить такой, вам нужно установить сторонний инструмент, такой как Cygwin .
Вы пытаетесь запустить команду Linux в командной строке Windows.
В Linux косая черта является разделителем пути. В Windows обратная косая черта является разделителем пути, а прямая косая черта обычно указывает на аргумент.
Поэтому Windows считает, что вы пытаетесь запустить команду с именем «.» и синтаксический анализ аргумента «/name.sh». Правильное соглашение будет «. \ Name.sh». Кроме того, Windows автоматически выполнит поиск вашей команды в текущем каталоге, чтобы вы могли просто ввести «name.sh».
Следующая проблема, с которой вы столкнетесь, заключается в том, что Windows не знает, что такое sh-скрипт, опять же, это Linux. Вы можете решить эту проблему, установив Cygwin, если вы действительно хотите или вам нужно запустить скрипт sh.