- 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.
Table of Contents
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:
- Install WSL
- Install a Linux distro
- 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:
-
Press the Windows Key + R shortcut keys to open the Run Command box.
-
Type in “optionalfeatures” and press Enter.
Open the Optional Features applet -
Select “Windows Subsystem for Linux” and “Virtual Machine Platform,” and then click Ok.
Enable WSL and Virtual Machine Platform The wizard will now install WSL.
-
When the installation is completed, click “Restart now.”
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:
-
When it restarts, press Windows Key + R again to open Run.
-
Type in “cmd” and press CTRL + Shift + Enter to run Command Prompt as administrator.
-
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 Note down the name of the distro you want to install.
-
Use the following command to install the preferred distro while substituting its name:
wsl --install -d [DistributionName]
Install a Linux distro in WSL The distro will now begin to download and install.
-
Set up a username and password.
Set up username and password -
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:
-
Press the Windows Key + R again to open Run.
-
Type in “cmd” and press CTRL + Shift + Enter to run Command Prompt as administrator.
-
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 -
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
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:
-
First, download and install Cygwin from their official website.
-
Once installed, run the Cygwin app.
-
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 -
Now, make the shell script file executable through this command:
chmod +x [ShellFileName].sh
Make the shell script file executable -
Now, use the following syntax to run the shell script file:
./[ShellFileName].sh
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.
Shell — это один из командных интерпретаторов, поставляемых вместе с ОС unix. Программа на языке Shell называется скриптом. Shell скрпитам указывают расширение *.sh и работают они в Unix системах. Если вам надо запустить shell скрипт в windows, то можно установить подсистему Linux Ubuntu или установить отдельно интерпретатор Shell для windows.
Допустим у вас есть скрипт hello.sh состоящий из одной команды.
echo "Hello World"
Чтобы его запустить, надо зайти в каталог, где расположен скрипт, набрать название интерпретатора sh и первым параметров указать ваш файл hello.sh.
sh hello.sh
Чтобы каждый раз не указывать интерпретатор в терминале, можно сделать скрипт исполняемым. Для этого необходимо:
- Указать интерпретатор внутри файла.
На первой строчке после #! прописывам путь к bash-интерпретатору, по-умолчанию это /bin/bash (посмотреть можно командой whereis bash). Содержмиое скрипта hello.sh получается таким:#!/bin/bash echo "Hello World"
- Сделать наш файл исполняемым. Для этого используется команда chmod +x и имя файла скрипта:
chmod +x hello.sh
Теперь можно запускать:
./hello.sh
Перед названием скрипта надо ставить точку и слэш, сделано для усложнения работы вирусов. Точка означает «текущий каталог», а слэш «/» разделитель между именем каталога и именем скрипта.
Перенести базы PostgreSQL на другой диск Windows
Если у вас установлен Postgres в конфигурации по умолчанию, то его базы хранятся в Program Files. Если есть необходимость освободить место на системном диске C, то можно перенести базы данных Postgres на другой диск.
504 gateway time-out nginx
Как исправить ошибку «504 gateway time-out» (Время вышло)
Разница между «service restart» и «service reload»
restart = stop + start, в свою очередь reload = перечитать файлы конфигурации не прерывая работы
phpDocumentor на Ubuntu
Запись об установке и использовании phpDocumentor — системе документирования исходных текстов на PHP.
ng serve не срабатывает слежение за файлами
sudo sysctl fs.inotify.max_user_watches=256000
Linux. Создание файла определённого размера
создание файла без реальной записи данных
fallocate -l 2G filename.ext
или (медленный вариант)
user@ubuntu:~$ dd if=/dev/zero of=filname.ext bs=100M count=5
5+0 записей считано
5+0 записей написано
скопировано 524288000 байт (524 MB), 3,09439 c, 169 MB/c
- https://tyapk.ru/blog/post/tretya-laba-os
Home
Windows
By
Anup Thapa
Files with the .sh
extension, i.e., shell scripts, are designed to be run by Unix shells such as Bourne or GNU Bash. If you attempt to run shell scripts in Windows, it won’t work as the commands won’t be recognized by default.
Instead, you’ll have to introduce a compatibility layer to be able to run such scripts in Windows. There are various ways to do this, with the popular ones being Windows Subsystem for Linux, Cygwin, and Git Bash.
In this article, we’ve listed all the necessary steps to run Shell Scripts in Windows using these methods.
Windows Subsystem For Linux
The first method is to install a Linux distro through the Windows Subsystem for Linux feature. Cygwin and Git are convenient, but users often have difficulty running complex shell scripts and Linux applications with them. As such, WSL is the recommended option. Here are the necessary steps for this:
- Press Win + R, type
optionalfeatures, and press Enter.
- Enable the Windows Subsystem for Linux and Virtual Machine Platform features, and press OK.
- After the changes are applied, restart the computer.
- When booting, press the BIOS key (Fn keys or Del).
- Go to the Advanced CPU Configuration or similar section and look for the virtualization option. It will be named something like AMD-V, SVM, VT-d, or VT-x.
- Enable the virtualization option if it isn’t already so, and press F10 to save the changes and exit.
- After booting, download and install the WSL2 Linux Kernel Update Package.
- Press Win + R, type
powershell
, and press Enter. - Execute the following command to set WSL 2 as the default version when installing new Linux distros:
wsl --set-default-version 2
- Open the WSL Store, select your preferred distro, and press Get to download it. If you’re unable to install WSL Linux Distros from the Microsoft Store, you can directly download and install them using these links provided by Microsoft.
- After it’s downloaded, press Open.
- On the first launch, the installation will take a couple of minutes.
- After the installation completes, enter a new UNIX username and password.
- Before anything else, it’s good practice to update and upgrade your packages. On Debian-based distros, you can do this with the following command:
sudo apt update && sudo apt upgrade
- Navigate to the location of the script file.
- Hold Shift, right-click, and select Open Linux Shell here.
- Enter
sh scriptname.sh
to run the shell script.
Note: For common WSL issues encountered both during and after the installation, we recommend referring to this troubleshooting guide from Microsoft.
Use Cygwin
Cygwin is a run time environment used to run code designed for Unix environments on Windows. Here’s how you can run shell scripts in Windows using Cygwin:
- Download and launch the Cygwin installer.
- Select Install from Internet as the download source.
- Specify the root directory to install Cygwin to. Also, select whether Cygwin should be available for all users or just the current one.
- Select the default options for local package directory and internet connection.
- For the download site, choose a mirror geographically close to you if possible. Otherwise, any mirror will do fine. The difference in download speed shouldn’t be anything major.
- Don’t select any packages for the time being. Just press Next and follow the on-screen instructions to complete the installation.
- Open the Cygwin64 Terminal and navigate to the location where the shell scripts are stored.
cd <scriptpath>
- Use the following command to run the shell script:
sh scriptname.sh
Use Git Bash
During its installation, Git optionally adds some UNIX tools to the PATH in Windows, with sh.exe
being one of them. Here’s how you can install Git and run shell scripts using Git bash:
- Download and install Git.
- During the installation, make sure to include Git bash and add Git to the PATH variable.
- After the installation is complete, navigate to the folder with the shell script.
- Right-click on an empty area and select Show More Options > Git bash here.
- Once again, use the
sh scriptname.sh
command to run the shell script.
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.
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.
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:
cd C:Users/Username/Desktop
This will change the directory to the desktop. Now type the following command to execute SH File:
sh appuals.sh
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:
Invoke-WebRequest -Uri https://aka.ms/wsl-ubuntu-1604 -OutFile Ubuntu.appx -UseBasicParsing
Downloading distro through Power Shell - The third method to download the distro is using the following curl command:
curl.exe -L -o ubuntu-1604.appx https://aka.ms/wsl-ubuntu-1604
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:
Installing and setting up ubuntu
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:
sudo apt update && sudo apt upgrade
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:
cd /mnt
This will mount your Windows drives. Now you can go to the location you want to:
cd c/Users/Username/Desktop/
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:
sh appuals.sh
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:
cd desktop
Note: Desktop can be the name of the folder where your file is located.
- Now type the SH executing command:
sh appuals.sh
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:
cd desktop
Note: Desktop can be the folder name that you are trying to access.
- Now simply type the name of the file with extension:
appuals.bat
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’.
Kevin Arrows
Kevin Arrows is a highly experienced and knowledgeable technology specialist with over a decade of industry experience. He holds a Microsoft Certified Technology Specialist (MCTS) certification and has a deep passion for staying up-to-date on the latest tech developments. Kevin has written extensively on a wide range of tech-related topics, showcasing his expertise and knowledge in areas such as software development, cybersecurity, and cloud computing. His contributions to the tech field have been widely recognized and respected by his peers, and he is highly regarded for his ability to explain complex technical concepts in a clear and concise manner.