Windows unix script files

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.

  1. Go to the Official Cygwin site to download the 32bit or 64bit setup file: CygwinDownload site for Cygwin
  2. 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.
  3. After installation, open Cygwin64 Terminal by double-clicking the shortcut on the desktop.
  4. 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

  1. Hold Windows Key and Press R to open Run, then type appwiz.cpl and Enter. Opening Programs and Features
  2. Click on the Turn Windows Features on or off on the left side. Opening Turn Windows features on or off option
  3. Scroll down to the bottom and tick Windows Subsystem for Linux and click Ok to install. Enabling Windows Subsystem for Linux
  4. 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:

  1. Hold Windows key and press R to open Run, type ‘ms-windows-store:‘ without the quotation marks and Enter. Opening the Windows Store
  2. Search for Ubuntu. Click on the one that is shown below and download it: Downloading Ubuntu from Windows Store
  3. The second method is to use the following Power shell command to download Linux distro: Downloading distro through Power Shell
  4. 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

  1. 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
  2. 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.

  • Type the following command to execute the SH file: Changing directory and executing the SH file
  • 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

  • Open the downloaded setup file to install Git. Go through the installation process and do check the options which you want and which you don’t.
  • Hold Windows key and Press S to open search function, type Git Bash and Enter. Opening Git Bash
  • Change directory to where your file is located by the following command:

    Note: Desktop can be the name of the folder where your file is located.

  • Now type the SH executing command: Executing SH file in Git Bash
  • 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.

  • Click on the File and choose Save in the list to save the changes. Saving the changes
  • Left-click on the SH file and press F2 key to rename the file. You can also right-click on a file and choose rename. Changing the extension of the file

    Change the extension from .sh to .bat and click Yes for the changes.

  • Hold Windows key and Press S to open search function, then type cmd and Enter.
  • Change the directory to the path where the file is located by using the cd command:

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

    How to run .sh or Shell Script file in Windows 10

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

    How to run .sh or Shell Script file in Windows 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.

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

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

    Date: July 15, 2019 Tags: WSL

    Windows Subsystem for Linux has no installed distributions

    Failed to Fork error with Ubuntu on Windows 10

    WslRegisterDistribution failed with error 0x8007019e and 0x8000000d – WSL

    [email protected]

    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.

    Как в Windows 10 запускать SH-скрипты без подсистемы Bash

    Большинству пользователей так или иначе приходилось сталкиваться со скриптами – мини-программами, используемыми обычно для чисто утилитарных целей. Наиболее распространены пакетные файлы CMD и BAT, однако иногда попадаются и другие типы скриптов, например, SH – сценарии, используемые прикладными программами в Bash. Несмотря на то, что предназначаются такие скрипты для Linux, благодаря интеграции подсистемы Bash они запросто могут быть выполнены и в Windows 10. Впрочем, если вы без подготовки попробуете запустить в «десятке» пакетный файл SH, то у системы не получится его обработать.

    Чтобы иметь возможность запускать в среде Windows SH-сценарии, вам нужно ставить подсистему Linux. Но можно пойти и другим путем, установив альтернативные интерпретаторы, например, Git Bash или Cygwin. Они позволяют компилировать и запускать Unix и Linux-сценарии в Windows, причем как в 64-разрядной, так и в 32-разрядной версии системы.

    Git Bash

    Приложение Git Bash доступно для скачивания с сайта разработчика git-scm.com/downloads. Скачав версию для Windows вашей разрядности, установите программу, проигнорировав многочисленные настройки в окне мастера (менять их нет смысла). После запуска приложения вы увидите окно командной строки, очень похожей на окно стандартной консоли CMD, только с другим приглашением ввода.

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

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

    Cygwin

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

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

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

    Читайте также:  Windows 10 iphone звонить
  • Оцените статью