Запуск скриптов linux в windows

Под GNU/Linux-дистрибутивы создано огромное количество полезных и удобных инструментов и приложений для обычных пользователей и разработчиков. Далеко не всё из этого доступно на Windows, но, к счастью, для ОС от Microsoft есть решения, исправляющие эту проблему.

WSL — официальная подсистема Linux внутри Windows

В Windows 10 существует крайне полезная вещь под названием Windows Subsystem for Linux (WSL). Она позволяет использовать GNU/Linux-среду прямо в Windows и запускать не только команды, но и, например, Bash-скрипты. Для использования WSL необходимо следовать инструкции ниже.

Шаг 1. Проверьте, подходит ли текущая версия Windows требованиям. Для этого нажмите сочетание клавиш Win+R, затем введите winver. Найдите строку «Сборка ОС» — она должна быть свежее версии 14316.

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

Шаг 2. Запустите стандартную утилиту PowerShell от имени администратора и введите в ней команду для включения WSL:

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

Шаг 3. Если версия Windows, определённая в первом пункте, свежее 18362, вы можете установить WSL 2, который в разы быстрее первой версии и обладает доработанным ядром. Введите команду ниже, если нужно установить WSL 2:

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

После этого скачайте и установите пакет обновления с официального сайта.

Шаг 4. Перезагрузите компьютер. Если была произведена установка WSL 2, введите в PowerShell от имени администратора следующую команду:

wsl —set-default-version 2

Шаг 5. После перезагрузки откройте фирменный магазин приложений Microsoft Store и найдите подходящий GNU/Linux-дистрибутив. Самым популярным является Ubuntu — вы можете установить любую версию из представленных в Microsoft Store.

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

Шаг 6. Как только установка завершится, найдите дистрибутив в меню «Пуск» и запустите его.

Шаг 7. Пройдите этап первоначальной настройки, введя имя нового пользователя и придумав пароль.

Шаг 8. Теперь различные GNU/Linux-команды можно выполнять, запустив дистрибутив, либо введя в командной строке wsl <команда>. Например, для просмотра всех файлов в текущей директории достаточно в командной строке выполнить wsl ls -a.

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

Обращу внимание на то, что путь к дискам в WSL отличается от такового в Windows. Вместо привычного C:/ используйте /mnt/c/. Также не забывайте про экранирование пробелов с помощью символа \ — это также пригодится при вводе путей к файлам.

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

Шаг 1. Загрузите X-сервер и установите его.

Шаг 2. Запустите его с помощью ярлыка на рабочем столе. В открывшемся окне выберите вариант Multiple windows, затем Start no client. Завершите настройку кнопкой Finish.

Шаг 3. Откройте дистрибутив через меню Пуск и выполните команду export DISPLAY=:0

Шаг 4. Запустив приложение с графическим интерфейсом в WSL, вы увидите новое окно прямо в Windows.

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

CoreUtils — лёгкий инструмент для запуска базовых команд

Плюс данной утилиты — возможность запуска не только на Windows 10, но и на более старых версиях ОС. Кроме того, она легка и не занимает много места. Не обошлось без недостатков — программа скудна на функционал и не обновлялась очень давно. Она не только не умеет запускать скрипты и приложения с GUI, но и поддерживает лишь самые базовые GNU/Linux-команды. Установка CoreUtils весьма проста.

Шаг 1. Скачайте утилиту с официального сайта.

Шаг 2. Следуйте инструкциям установщика.

Шаг 3. Откройте «Панель управления», в разделе «Система и безопасность» выберите пункт «Система». На панели слева откройте «Дополнительные параметры системы». Нажмите кнопку «Переменные среды» и в открывшемся окне найдите область с заголовком «Системные переменные». В случае, когда там есть переменная Path, выберите её, нажмите «Изменить» и далее создайте новую строку. Содержимым этой строки должен быть путь к папке, который был указан при установке. Если вы ничего не меняли, то введите следующее:

C:\Program Files (x86)\GnuWin32\bin

Переменной Path нет? Тогда для начала создайте её кнопкой «Создать», затем в поле имени введите Path, а в поле значения — строку выше.

Шаг 4. Запустите командную строку и выполняйте команды прямо там.

Cygwin — запуск команд и Bash-скриптов

Ещё одна утилита, схожая с CoreUtils, но обладающая более широким функционалом — в том числе и возможностью запуска скриптов. Из минусов — немалый вес и более сложная установка. Разумеется, не идёт ни в какое сравнение с максимально удобным WSL, но для базовых команд вполне подойдёт.

Шаг 1. Загрузите Cygwin и запустите установку.

Шаг 2. Выберите Install from Internet, укажите директории для установки и загрузки пакетов, а также любой подходящий сайт из списка для скачивания файлов.

Шаг 3. В процессе установки можете выбрать необходимые пакеты, либо сразу нажать «Далее», оставив базовый набор.

Шаг 4. Откройте «Панель управления», в разделе «Система и безопасность» выберите пункт «Система». На панели слева откройте «Дополнительные параметры системы». Нажмите кнопку «Переменные среды» и в открывшемся окне найдите область с заголовком «Системные переменные». В случае, когда там есть переменная Path, выберите её, нажмите «Изменить» и далее создайте новую строку. Содержимым этой строки должен быть путь к папке, который был указан при установке. Если вы ничего не меняли, то введите следующее:

C:\cygwin64\bin

Переменной Path нет? Тогда для начала создайте её кнопкой «Создать», затем в поле имени введите Path, а в поле значения — строку выше.

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

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

Шаг 6. Для удаления Cygwin достаточно удалить папку, в которую программа была установлена, а также (по желанию) значение из переменной Path по методу, обратному тому, что был описан в 4 шаге (не удаляйте саму переменную).

  • To run shell scripts on Windows, you must enable WSL and Virtual Machine Platform, install a WSL distro, and use “Bash Script.sh” to execute it.
  • Alternatively, use third-party tools like Cygwin, Cmder to run Linux commands on top of Windows OS.

If you have worked with Linux distributions and repositories, you would know what shell scripts are. To run shell scripts on top of a Windows computer can be challenging, as the process is not quite straightforward.

Shell scripts are a piece of code written in plain text but have the “.SH” file extension. These are usually used to automate tasks and execute Linux or Unix packages. These are written in Bash and start with “#! /bin/sh“.

You do not need to install a Linux or Unix distribution alongside your Windows operating system to run a shell script. In this article, we’ll show you how to run a shell script on a Windows PC.

On This Page

What are Shell (.SH) Files

The Linux/Unix operating system uses shell or .SH script files to perform certain tasks. In comparison, it can be substituted by Windows batch files for the Windows operating systems, which are used to execute commands on a computer.

The Batch language is a simple and interpreted programming language, unlike C++ or C#. However, you do not have to translate a shell script file to batch to perform similar tasks on a Windows computer, as you do on a Linux PC.

There are different methods to run the same .SH file on a Windows computer as on a Linux system. Let us show you how to run a shell file on a Windows PC.

Run Shell Script (.SH) File on Windows

There are both native and third-party methods to run shell files on a Windows computer. You can use Cygwin, or a third-party tool of your choice, to run a shell script on Windows OS. Alternatively, you can install the Windows Subsystem for Linux feature on Windows and then execute the shell script file through it.

Below you’ll find the methods to run the file using both methods.

Run Shell Script File using Windows Subsystem for Linux (WSL)

This section has been divided into 3 steps to make the process easier to understand. You must do the following 3 things to run a shell script file in the given order:

  1. Install WSL
  2. Install a Linux distro
  3. Run the shell script file

Note: If you are performing these steps on a Virtual Machine, then you will need to enable Nested Virtualization.

Install WSL

Use the following steps to install WSL on your computer:

  1. Press the Windows Key + R shortcut keys to open the Run Command box.

  2. Type in “optionalfeatures” and press Enter.

    Open the Optional Features applet

    Open the Optional Features applet
  3. Select “Windows Subsystem for Linux” and “Virtual Machine Platform,” and then click Ok.

    Enable WSL and Virtual Machine Platform

    Enable WSL and Virtual Machine Platform

    The wizard will now install WSL.

  4. When the installation is completed, click “Restart now.”

    Restart computer

    Restart computer

Once the computer restarts, it is time to install a Linux distro.

Install a Linux Distribution

Use the following steps to install a Linux distribution:

  1. When it restarts, press Windows Key + R again to open Run.

  2. Type in “cmd” and press CTRL + Shift + Enter to run Command Prompt as administrator.

  3. Run the following command to obtain a list of available Linux distros:

    wsl --list --online

    Get list of all available Linux distros in Command Prompt

    Get list of all available Linux distros in Command Prompt

    Note down the name of the distro you want to install.

  4. Use the following command to install the preferred distro while substituting its name:

    wsl --install -d [DistributionName]

    Install a Linux distro in WSL

    Install a Linux distro in WSL

    The distro will now begin to download and install.

  5. Set up a username and password.

    Set up username and password

    Set up username and password
  6. Restart the computer.

Now, the next step is to simply run the shell script file.

Run the Shell Script File

Follow the simple steps below to run the shell script file on a Windows PC:

  1. Press the Windows Key + R again to open Run.

  2. Type in “cmd” and press CTRL + Shift + Enter to run Command Prompt as administrator.

  3. Use the CD cmdlet to change the directory to the location of the shell script file.

    CD [PathToShellScriptFile]

    Change directory to the shell script file location

    Change directory to the shell script file location
  4. Now, use the following command to run the shell script file while substituting [ShellFileName] with the complete and correct name of the shell file:

    Bash [ShellFileName].sh

    Run the shell script file using Windows Subsystem for Linux

    Run the shell script file using Windows Subsystem for Linux

This is how you run a shell script (.SH) file on a Windows computer using WSL.

If this seems like a lengthy process for you, then you can also use the alternative method given below.

Run Shell Script File using Third-Party Tools

You can also run a shell script file on a Windows computer using a third-party tool. In the steps below, we have used Cygwin.

Follow these steps to run a .SH file on a Windows PC:

  1. First, download and install Cygwin from their official website.

  2. Once installed, run the Cygwin app.

  3. In the Cygwin terminal, use the CD command to change the directory to the shell script file location.

    Note: In Cygwin, the syntax to change the directory is different from Command Prompt or PowerShell. Use the following command syntax and example in the image to change your directory in Cygwin.

    CD /cygdrive/[driveLetter]/[Subfolder1]/[Subfolder2]

    Change directory to the shell script file location in Cygwin

    Change directory to the shell script file location in Cygwin
  4. Now, make the shell script file executable through this command:

    chmod +x [ShellFileName].sh

    Make the shell script file executable

    Make the shell script file executable
  5. Now, use the following syntax to run the shell script file:

    ./[ShellFileName].sh

    Run shell script file on Windows using Cygwin

    Run shell script file on Windows using Cygwin

These are the two methods to run shell script files (.SH) on a Windows PC. Of course, there are many other third-party tools available that allow you to run Linux and Unix files on a Windows computer.

Frequently Asked Questions (FAQs)

How to create a shell script (.SH) file?

I you know what you want to write inside the shell script file, all you need to do is follow these simple rules:
– Create a new notepad file
– Start the script with “#! /bin/sh”
– Write the code below it
– Save the file with a “.sh” extension
– To run the script, type “bash [FileName].sh” after navigating to the folder.

Can I run shell scripts on Windows?

Yes, shell script files can be executed on a Windows computer using Windows Subsystem for Linux, or third-party tools like Cygwin, kiTTY, ConEmu, Cmder, etc.

Why use shell scripts on Windows?

Shell scripts are used to perform repetitive tasks to save time and resources. They are also used to automate tasks. With the WSL feature, Microsoft has opened doors to natively run shell scripts on Windows operating systems.

Are you interested in working with shell scripts on Windows? Thanks to a recent addition by Microsoft, you can now use Windows Subsystem for Linux to make this happen. 

Once you enable shell scripts in Windows 10, you can start creating shell scripts of your own. Shell scripts are great for automating simple tasks. You can also work on open-source Linux-based projects if that’s an area of interest to you. Finally, you’ll learn how to execute shell scripts on Windows 10. Continue reading to learn more.

What is Linux?

Linux is an open-source operating system that is highly popular among computer enthusiasts. Linux competes with other computer operating systems like Microsoft’s Windows, Apple’s macOS, and mobile operating systems like Android and iOS. 

The Linux operating system was originally developed by Linus Torvalds back in 1991. The Linux kernel was designed as a Unix-like operating system. Unix was an early operating system created by Bell Labs in 1969. Today, modern Linux distributions are still Unix-like, meaning they retain the basic structure and properties that Unix had. An example of a non-Unix operating system would be Microsoft Windows.

The top Linux distributions have changed over the years, but as of 2022, Ubuntu, Debian, CentOS, Fedora, and Red Hat rank as the top 5 most popular options. 

What is Bash?

When Linus Torvalds created Linux, he included a Unix shell called Bash. Bash had been created just two years before, in 1989 by Brian Fox. Bash has been the longtime default for Linux and was also the default for Apple macOS until it was replaced by Z shell in 2019. 

Until 2016, Windows users could not use the Linux kernel or Bash at all. Windows first introduced the Windows Subsystem for Linux (WSL) beta with Windows 10 version 1607 update. About a year later, in October 2017, WSL was fully released in Windows 10 version 1709. Microsoft developed WSL for hobbyists and developers who want to work on open-source Linux-based projects. 

It’s important to note that WSL is not preinstalled on Windows 10. If you would like access to create and run shell scripts on Windows 10, you will need to manually install WSL or join the Windows insider program. 

What is a shell script?

A Shell script is a type of script that cannot be run without a Unix shell. Further, a shell script is a series of commands that are executed line by line by the command line. 

You can use shell scripts to automate processes and avoid repetitive tasks. Instead of manually completing each step in a series, you can execute a script, and the command line will handle the rest.

For example, if you find yourself regularly stopping processes that are hogging your CPU, you can automate this process with a script. When you execute the script, it may be designed to find a set of processes using CPU resources and request to kill them. 

Enabling shell scripts in Windows 10

  1. Click on the Start (Windows) button and enter “Control Panel” into the search bar. Click Open on the Control Panel result on the right-hand side.
Search for Control Panel
  1. Within the Control Panel window, find and click on Programs.
Control Panel options
  1. Now, from the Programs window, find Click Turn Windows features on or off underneath the Programs and Features header.
Turn Windows features on or off
  1. In the Windows Features window, scroll to the very bottom of the window. Check the Windows Subsystem for Linux option. Then click OK.
Enable Windows Subsystem for Linux to be able to run shell scripts
  1. Windows will automatically install the necessary files. When the installation is complete, select Restart Now.
Restart Windows
  1. When your computer restarts, you need to install Ubuntu from the Microsoft store.
Install Ubuntu to run shell scripts on Windows
  1. After installation, make sure you open Ubuntu and see it up. You are now ready to use scripts on your Windows 10 machine.

If you encounter any issues with Ubuntu or bash commands not working correctly, you may want to check that Virtualization is turned on in your BIOS. The most updated WSL version, WSL 2, runs the Linux kernel using virtualization technology. This means a virtual machine needs to be able to run on your system.

Now that Windows Subsystem for Linux and Ubuntu has been installed, you are ready to start creating shell scripts in Windows 10. You may be tempted to write bash scripts with Notepad, but this is not recommended. Because Notepad is designed for Windows/DOS systems, the line endings will differ from those that are found at the end of Unix/Linux line endings. 

Text editors for shell scripts

You should use software that is designed to convert to Unix/OSX end-of-line characters. The best open-source software available for this is Notepad++. Amazingly, Notepad++ is lovingly maintained and developed by a single individual, Don Ho. 

If you try Notepad++ and don’t like it, you can try another fan favorite, nano. Nano is a text editor for Unix/Linux systems. You can easily create shell scripts that will run in bash, using nano. Download nano to get started.

Example shell scripts

Let’s look at some basic shell scripts, so you can learn more about what you are going to be coding and see how some formatting and syntax work.

1. Hello World!

echo "Hello World!"

This script will print out the infamous Hello World! Notice that echo can be used as a print command when not combined with any other modifiers. It will print the string on a new line. If you add the -n modifier, the output will print on the same line. 

2. Sum two numbers

If you want to do some basic arithmetic, you might have a script that looks like:

# Add two numbers together
((sum=25+35))

# Print the sum of the numbers
echo $sum

Note that the # symbol is used to make comments that are not expressed. The output of this script will print the sum of 25+35, which is 60. 

3. Take user input

The following script will ask for the user’s name and then use the read command to take the user’s input. Then the user’s name is passed into the following expression, ultimately welcoming you to Windows Subsystem for Linux. 

echo "What is your name?"
read name
echo "Welcome $name to Windows Subsystem for Linux."

Write basic shell scripts in Windows 10

Continue reading to learn how to write basic shell scripts in Windows 10 using Notepad++.

  1. Click the Start button and search for “Notepad++” and click Run as administrator on the right-hand side.
Search Notepad++
  1. Now you can create your script.
Write your bash script in Notepad++ on Windows
  1. Once your script is complete, you need to use the EOL Conversion option available in Notepad++. Click Edit and locate EOL Conversion from the dropdown menu. Hover over this option and then select UNIX/OSX Format from the next dropdown menu.
Change EOL Conversion to UNIX/OSX format
  1. Now select File and then Save As. Make sure to name your file something you will recognize and add .sh to make it a shell script file.

Save the sh file before you run it on Windows

  1. Once the shell script is saved, continue to the next section to learn how to run your own shell scripts.

How to run shell scripts (.sh files) on Windows 10

You’ve created your first shell scripts, and it’s time to execute the sh file. Remember that when using WSL, you can only use Linux commands and utilities. Windows 10 programs will not work in bash scripts. To execute a script file, follow these step-by-step instructions:

  1. Click on the Start (Windows) button and enter “Command Prompt into the search bar. Click Run as administrator on the Command Prompt result on the right-hand side.
  2. Navigate to the folder where the script file is saved. You move around in the command prompt using the cd command. For example, if you want to access the Documents folder, you would enter the following and press Enter:

    cd C:\Users\Username\OneDrive\Documents

    Note: Username would be the username that you set up for yourself when you registered your computer. 

Navigate to the location of the sh file in Command Prompt
  1. Now enter bash file-name.sh, where file-name is the whatever you’ve named your script file. 

    bash file-name.sh

    The script will execute, and if there are any outputs or print statements included in the script, the output will be returned.

Bash scripts running on Windows 10

You’ve made it far and learned a ton of information in one go. Command-line utilities, different operating systems, and learning to write and execute shell scripts can be difficult topics. In fact, these topics will take time to master. You have a ton of learning to do for scripting, but resources are available to help you all over the internet. 

Within this guide, you learned the basics of Linux and Bash. You learned what shell scripts are and that you need to specifically enable Windows Subsystem for Linux (WSL) to use them. You learned how to create shell scripts using Notepad++ and how to execute the scripts in bash. Enjoy experimenting!

Bash Shell scripts are text files ending with the .sh extension, and it contains coded information written for the Linux operating system. Script files are designed to perform a designated task when run through a computer program called BASH in the Linux platform.

However, the Windows operating system does not know the command language used inside the shell script files and therefore fails to execute shell scripts directly. If you want to know how to run a shell script in Windows, you have come to the right place. Read on to learn more about bash scripts.

What are Shell Scripts or SH files?

How to Run Shell Script in Windows

Shell script files (or SH files) contain one or more commands written in the BASH (Bourne-Again Shell) language and are used by multiple Linux programs. Software engineers developed these files to ease the workload and divide individual operations into numerous script files. Hence, they have a crucial role to play while creating a short but powerful computer program.

In Linux, these script files can be run in a terminal window by simply navigating to their location and typing their filename. In Windows, however, they require additional software or a Linux-like environment to execute bash scripts as batch files.

A Linux environment can be implemented in Windows through the latest inclusion of the Windows Subsystem for Linux (WSL) for Windows 10/11, through which various Linux script files or GUI can be executed through the Windows Bash Shell. Now without further ado, let us show you how to run shell scripts in Windows.

Batch files (or .bat files) are small coded programs for Windows that perform automated tasks with minimal effort. Similarly, a .sh script file performs the same job for Unix or Linux systems through the bash shell. Bash scripts consist of command line inputs (such as cd, md, mkdir) bundled together to perform at once upon execution. Moreover, it is possible to run Linux scripts in Windows 10/11 in the following ways:

1] Execute Shell Script file using Windows Subsystem for Linux

It is not possible to run script files through the command prompt or PowerShell terminal provided by Windows directly, but it is possible to run native Bash shell through the latest integration of WSL or Windows Subsystem for Linux being provided from Windows 10 Insider Preview Build 14316. The process involves a lot of steps as a whole, so we have divided it into 4 parts.

Part 1: Enable WSL and developer settings from Windows features:

  • First, we need to enable the WSL Windows feature through the developer settings. It comes bundled with the Windows operating system and doesn’t require extra data from the internet. Enable developer settings through the steps below.
  • Open Start Menu and click on the Gear icon to open the Settings app.
Update & Security in Settings app
  • Head over to the Update & Security section from the Settings menu.
Enable Developer settings
  • Click on the “For Developers” tab in the left pane and turn on the Developer mode using the button as shown.
Enable Developer Settings
  • Select OK on the warning message.
Search for Windows Features
  • Inside the “Find a setting” search bar, type Windows features and click the option to “Turn Windows features on or off.”
Enable Windows Subsystem for Linux
  • You will see a window pop-up listing all the different on-demand future or deprecated Windows features that users can enable anytime. Find Windows Subsystem for Linux among them, and mark the checkbox beside it. Click on OK to confirm the changes and proceed.
Install Windows Subsystem for Linux
  • Windows will spend some time Searching for the required files to enable the Windows subsystem.
Applying changes
  • After acquiring the Windows files, the installation manager will apply changes, so wait for it patiently.
Restart Now to finish installation of WSL
  • On successfully completing the entire process of adding the Windows Bash, You will be asked to Restart your computer. You can either Restart now or later on your own, depending on if you have some scheduled tasks left.

Part 2: Download Ubuntu from the Microsoft Store and integrate with WSL:

  • After restarting, open the Microsoft Store from the Start Menu.
Ubunty search result in the Microsoft Store
  • Search for Ubuntu in the App Store.
Download Ubuntu from the Microsoft Store
  • Click on Get to download the Linux distro and wait patiently.
Open Ubuntu in Windows Start
  • Upon the completion of installation, open Ubuntu from the Start menu (From the recently added app section)
Initialize Ubuntu with WSL
  • A command prompt window opens up, and Ubuntu begins its original installation on your hard disk and its integration with the WSL to get access to Windows files.
Finish installation by entering username and password
  • The Windows Bash window asks you to create an account (separate from your original Windows account). Type your desired username and password as login credentials. Remember them properly as they will be required later.
  • After completion, you can run Bash scripts, Linux commands (sed, awk, mkdir), Linux tools (nano, vi, python) directly on Windows. You also access the Linux filesystem on Windows.

Part 3: Initialize the Newly installed Linux Distro:

Upgrade the Linux Distro in Windows
  • Most Linux distro downloaded from the app store arrive with a minimal package catalog. You need to update and upgrade these packages through these commands:sudo apt update && sudo apt upgrade. Internet connectivity is required for this process to download extra packages.

Part 4: How to run shell script in Windows Command Prompt

  • Head over to the location in your Windows OS where the script files are stored as text files.
Open shell script in Windows command prompt
  • Hold down the Shift key and right-click on an empty space inside the folder. Click on the Open command prompt here. In newer Windows installation, click on Open PowerShell Window here.
  • Type bash inside the command prompt window or the power shell interface. Windows redirects you to the bash shell, and a new line opens up in the terminal window. This indicates that the environment has changed from Windows to BASH.
Open script shell files in Windows Powershell
  • Type sh yourfilename.sh inside the terminal window, where “yourfilename” is the name of the sh file, followed by file extensions.
  • Through the same process, you will get to know how to run script file in Windows PowerShell.

2] Using Cygwin to run Shell Script files

The Official Cygwin application is a free and open-source command-line interface for Windows. With it, Linux and Unix programs can be compiled and run on Windows using a Linux-like interface similar to the original Linux BASH. Let us see how to run shell script in Linux from Windows through Cygwin:

Official Cygwin website
  • Head over to the official Cygwin website. Look for executable Windows files (setup-x86_64.exe) and download either the 32-bit or 64-bit version of Cygwin.
  • Open the downloaded installation file from the Downloads folder, and follow the procedure as instructed by the on-screen steps. There are different options in the installation process, so make your choice accordingly.
  • If you have installed the 64-bit version of Cygwin, open the Cygwin64 Terminal by double-clicking its shortcut on your desktop.
Run Cygwin Terminal
  • The terminal will have access to any files on your pc, so provide the pathname (the folder where your script file is stored) in the following way: cd C:Users/Username/Desktop
  • After you change the directory, it is time to execute shell scripts through the sh command: sh yourfilename.sh, where “yourfilename” is the name of the sh file, followed by file extensions.

3] Execute Shell Script using the Git command line for Windows

Git is a distributed version control system tool that is free and open-source, and it is available for use on all operating systems. The usefulness of Git is given in detail below:

  • Changes in any set of files can be tracked using Git, which is most commonly used to coordinate the efforts of multiple programmers who are working together on the source code during the development process. 
  • Rapidity, data integrity, and support for non-linear distributed workflows are just some of its primary objectives (thousands of parallel branches running on different systems).

Linux and macOS computers come pre-installed with Git as a command-line tool, which is the default. However, you can also get it from the official website, which has versions for all operating systems. So let us see how to run shell script in Windows git bash:

Git Windows official webpage
  • Head over to the Official Git version control page by opening your browser and copying the given link: Download from here
  • Click on the Windows link to download the git command line for your Windows platform.
Enable Git Context menu options
  • Go to the Downloads folder and open the setup file to start installing git. Go through the installation process by following the on-screen instructions, and make your choices accordingly.
  • During the installation procedure, Git will install a context menu entry through which it becomes accessible to run shell script files from anywhere on the computer. Make sure to check that option in the installer.
Open script files using Git Bash Here
  • To run a script file, simply head over to the folder where the .sh file resides. Right-click on the folder name and select “GIT Bash Here.”
  • The GIT command terminal known as the git bash appears, and the working location is already set to your script file folder.
Run Script files in Git Command Line Windows
  • Run the script file using the command: sh filename.sh (The filename can be replaced with the original sh file name, followed by the file extensions)

4] Convert Script Shell files to Windows executable BAT files

This approach is not advised for typical users, but rather for those who are well-versed in the commands of scripts and batch files (bat files). For starters, we can simply update the format and extension of the SH file.

It does need the knowledge of how to translate a script file into a batch file, therefore you should avoid using this approach unless you are familiar with the formats of both of these files.

For the sample code modifications, we will demonstrate the straightforward procedures that must be followed.

  • Batch files are simple scripted programs for Windows, and they are similar to Linux shell scripts. In Windows, a batch file can be executed by simply double-clicking on it.
  • Firstly, we need to open a Linux sh script file using a text editor such as Notepad.
  • Double-click on the sh file. When Windows says it can’t find a file to open it, click on More Options, and click on Notepad.
Remove the first line of bash files
  • The first line of the script file must be something like the one given below: #!/bin/bash
  • Remove this shebang line from the code.
  • If you are an expert script file coder, analyze the Linux codes used there and think of an alternative Windows version of the code to replace it with.
  • Save the script file using Ctrl + S.
Rename sh file to bat file
  • Left-click on the Bash shell file, and press F2 to rename the file extensions. Modify the extension from .sh to .bat, press Enter and click Yes to confirm the changes.
Confirm renaming changes
  • Open the Windows Run Window using the Win + R shortcut. Inside the search bar, type cmd to open the command prompt terminal.
Run Command Prompt from Run
  • Change the directory to the folder path where the SH file is stored using cd folder name.
Run batch files from Windows Command Prompt
  • Execute the translated batch file using the command filename.bat
  • Do note that the commands that worked for Linux (such as comment notifier #) will not work for Windows, and might cause a syntax error when run. Therefore proper translation skill is important.

Запуск bash скриптов на Windows может показаться сложной задачей для пользователей, привыкших работать в операционной системе Linux. Однако, современные инструменты позволяют легко и безболезненно запустить и выполнить bash скрипты на Windows. В этой статье мы рассмотрим подробную инструкцию, которая поможет вам разобраться в этом процессе.

Первым шагом для запуска bash скриптов на Windows является установка и настройка Git Bash – эмулятора командной строки, который позволяет использовать bash команды в среде Windows. Для этого вам нужно скачать Git Bash с официального сайта и следовать инструкциям по установке.

После установки Git Bash вам нужно открыть его и настроить рабочую директорию, в которой будут находиться ваши bash скрипты. Для этого введите команду «cd /c/path/to/your/directory» в командной строке Git Bash, заменив «/c/path/to/your/directory» на путь к вашей рабочей директории.

Примечание: Путь к рабочей директории на Windows начинается с буквы диска, например «C:\path\to\your\directory».

Теперь, когда вы настроили рабочую директорию, вы можете создать и запустить ваш bash скрипт. Для создания скрипта создайте новый файл с расширением «.sh» в вашей рабочей директории и откройте его в текстовом редакторе. Напишите свой bash скрипт в открытом файле, используя bash-синтаксис. Затем сохраните файл.

Теперь, чтобы запустить ваш bash скрипт, вернитесь в командную строку Git Bash и введите команду «./your_script.sh», заменив «your_script.sh» на имя вашего скрипта. Команда «./» указывает на то, что скрипт находится в текущей директории.

Содержание

  1. Установка WSL
  2. Установка и настройка баш-оболочки
  3. Создание bash скрипта
  4. Добавление скрипта в переменную PATH
  5. Запуск bash скрипта на Windows

Установка WSL

Для запуска bash скриптов на Windows необходимо установить WSL (Windows Subsystem for Linux), который предоставляет среду выполнения Linux в операционной системе Windows. Следуйте инструкции ниже, чтобы установить WSL на вашем компьютере:

  1. Откройте меню «Пуск» и найдите «Настройки».
  2. В разделе «Настройки» выберите «Обновление и безопасность».
  3. В меню слева выберите «Разработчикам».
  4. В разделе «Использование разработчика» выберите «Режим разработчика».
  5. Подождите, пока Windows закончит установку необходимых компонентов.
  6. Перейдите в «Пуск» и найдите «Запуск».
  7. Введите команду «wsl» и нажмите клавишу Enter.
  8. Следуйте инструкциям по установке дистрибутива Linux (например, Ubuntu) из Microsoft Store.
  9. После установки запустите WSL, и вам будет предоставлен доступ к Linux-среде в командной строке.

Теперь у вас есть установленная среда WSL, и вы можете запускать bash скрипты на вашем компьютере Windows. Откройте командную строку WSL и выполните команду «bash», чтобы использовать оболочку bash для выполнения скриптов.

Примечание: Установка WSL требует наличия актуальной версии Windows 10, начиная с версии 1709 (осеннее обновление Windows 10). Если у вас установлена старая версия Windows, вам необходимо обновить систему до актуального пакета обновления для установки WSL.

Установка и настройка баш-оболочки

Для того чтобы запустить bash скрипт на операционной системе Windows, необходимо установить и настроить баш-оболочку. Вам понадобится следовать указанным ниже шагам:

Шаг 1: Скачайте и установите Ubuntu для Windows (WSL) с официального сайта. WSL позволяет запускать Linux-приложения на Windows и включает в себя баш-оболочку. Убедитесь, что у вас установлена версия Windows 10 или выше.

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

Шаг 3: Обновите пакеты Ubuntu, выполните следующую команду в терминале:

sudo apt update && sudo apt upgrade

Шаг 4: Установите обновленные пакеты, которые необходимы для работы баш-оболочки. Выполните следующую команду:

sudo apt install bash

Шаг 5: Убедитесь, что баш-оболочка установлена правильно, выполнив следующую команду:

bash --version

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

Шаг 6: Теперь вы можете запускать bash скрипты на Windows, используя команду bash перед именем скрипта. Например, чтобы запустить скрипт с именем «myscript.sh», выполните следующую команду:

bash myscript.sh

Теперь вы можете приступить к созданию и запуску bash скриптов на операционной системе Windows. Удачи в работе с баш-оболочкой!

Создание bash скрипта

Для создания bash скрипта вам понадобится текстовый редактор. Вы можете использовать любой удобный для вас редактор, например, Notepad++ или Visual Studio Code.

Создайте новый файл с расширением .sh, например, script.sh, и откройте его в текстовом редакторе.

Первая строка в скрипте должна начинаться со шебанга (shebang) – символа # и пути к исполняемому файлу bash:

#!/bin/bash

Шебанг говорит операционной системе, что этот файл должен быть выполняемым скриптом с использованием bash.

После шебанга вы можете начать писать команды вашего скрипта в новых строках. Например, вы можете использовать команду echo для вывода текста:

echo «Привет, мир!»

Текст в кавычках будет выведен в консоли при выполнении скрипта.

Вы также можете использовать переменные, условные операторы, циклы и другие конструкции языка bash для создания более сложных скриптов.

Когда вы закончите писать свой скрипт, сохраните файл. Теперь ваш bash скрипт готов к выполнению.

Добавление скрипта в переменную PATH

Когда вы хотите выполнять скрипт из любой директории в терминале, вам необходимо добавить путь к скрипту в переменную PATH операционной системы Windows. Это позволит системе находить скрипт, когда вы вводите его имя в командной строке.

Чтобы добавить скрипт в переменную PATH, следуйте инструкциям:

  1. Найдите местоположение вашего bash скрипта на вашем компьютере.
  2. Откройте «Контрольная панель» и найдите раздел «Система и безопасность».
  3. Выберите «Система» и затем «Дополнительные параметры системы».
  4. В диалоговом окне «Свойства системы» выберите вкладку «Дополнительно» и нажмите кнопку «Переменные среды».
  5. В секции «Переменные среды» найдите переменную «Path» и выберите ее.
  6. Нажмите кнопку «Изменить», чтобы изменить значение переменной «Path».
  7. В диалоговом окне «Изменение системной переменной» нажмите кнопку «Новый» и добавьте путь к вашему скрипту. Например, «C:\путь\к\скрипту».
  8. Нажмите «ОК» во всех диалоговых окнах, чтобы сохранить изменения.

Теперь ваш скрипт будет доступен из любой директории в командной строке Windows, вводя его имя без указания полного пути.

Запуск bash скрипта на Windows

Запуск bash скрипта на операционной системе Windows может быть немного сложнее, чем на Linux или macOS, но все же возможен. Ниже представлена подробная инструкция по запуску bash скриптов на Windows:

  1. Установите Windows Subsystem for Linux (WSL) — инструмент, позволяющий запускать подсистемы Linux на Windows. Для этого откройте «Панель управления» и выберите «Программы и компоненты». Затем найдите «Включение или отключение компонентов Windows» и установите галочку напротив «Windows Subsystem for Linux». После установки перезапустите компьютер.
  2. Установите дистрибутив Linux в WSL. Можно выбрать любой дистрибутив Linux, такой как Ubuntu, Debian, или Fedora, скачав его из Microsoft Store. После установки потребуется создать имя пользователя и пароль для доступа к дистрибутиву.
  3. Запустите WSL, открыв командную строку или терминал с установленным дистрибутивом Linux. Можно найти установленный дистрибутив Linux в меню «Пуск» или воспользоваться поиском.
  4. Перейдите в каталог, где находится ваш bash скрипт, с помощью команды cd. Например, если ваш скрипт находится в каталоге «Documents», выполните команду cd Documents.
  5. Запустите ваш bash скрипт с помощью команды bash script.sh. Здесь «script.sh» — название вашего скрипта. Убедитесь, что скрипт имеет права на выполнение, иначе выполните команду chmod +x script.sh.

Теперь вы можете запускать bash скрипты на Windows с помощью WSL. Этот способ позволяет вам использовать и запускать скрипты, написанные для Linux, на операционной системе Windows. Не забывайте, что для использования WSL вам понадобится установленный и настроенный дистрибутив Linux внутри WSL.

Другие наши интересноые статьи:

  • Запуск программы в безопасном режиме windows 10
  • Запуск скрипта при загрузке windows
  • Запуск программ windows на linux ubuntu
  • Запуск скрипта при запуске windows 10
  • Запуск программы автоматически windows 10

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии