Bash скрипты для windows

Разработчикам, системным администраторам и девопсам часто нужно выполнять одни и те же операции на компьютере или на сервере: следить за количеством свободного места, находить в логах ошибки и информацию о сбоях, смотреть, выполняются ли нужные программы в фоне и так далее. Это можно каждый раз делать вручную, а можно автоматизировать и запускать системный скрипт, который будет делать всё то же самое по одной команде. Для этого используют специальные файлы с набором команд — bash-скрипты, которые работают в ОС Linux и Unix, в том числе mac OS. На Windows такое тоже есть, но там всё работает чуть иначе. Рассказываем, что такое bash-скрипты и как ими пользоваться. 

Что такое bash-скрипт

Bash-скрипт — это файл с последовательностью команд, которые компьютер выполняет по очереди, строка за строкой. Если написать и сохранить эти команды в файл, можно повторять этот сценарий сколько угодно раз, просто запустив файл, а не вводя их каждый раз в командную строку.

Командами для таких скриптов служат:

  • команды и внутренние программы операционной системы;
  • любые исполняемые файлы на компьютере, часто вместе с дополнительными параметрами.

Bash-скрипты пишутся на скриптовых языках Bash и Shell (если точнее, то Bash — одна из разновидностей Shell). Эти языки поддерживают переменные, условные операторы, циклы и функции, благодаря чему на них можно писать сложные сценарии.

Bash (Bourne Again SHell) — это также командный интерпретатор, то есть оболочка командной строки, которая служит интерфейсом для взаимодействия пользователя с операционной системой. Bash распознаёт введённые команды, выполняет их и интерпретирует выходные данные для пользователя.

Проще говоря, всё, что можно выполнить в командной строке, можно использовать как команду в bash-скрипте.

Почему командная строка, а не удобный графический интерфейс

Большинство скриптов и настроек для их запуска делается в системах, основанных на Linux и UNIX. Всё дело в том, в этих операционных системах на первом месте стоит командная строка и управление текстовыми командами через терминал. В буквальном смысле эти операционки управляются текстом и выдают текст.

Графическая оболочка подобных систем — это надстройка над ядром. По сути, все эти кнопочки, иконки, стрелочки и поля ввода — это удобный способ давать компьютеру те же самые текстовые команды. Обычным пользователям нужны эти кнопочки, чтобы было интуитивно понятно, куда нажимать; но компьютеру они не нужны — внутри себя он оперирует текстовыми командами.

Это мы говорили про операционные системы семейства Linux, UNIX-подобные системы и Mac OS.

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

Поэтому мы сначала расскажем, про bash-скрипты на Mac OS и Linux, а потом поговорим про Windows.

Что можно делать с помощью bash-скриптов

Вот для чего используют bash-скрипты в народном хозяйстве:

  • Автоматизация повторяющихся задач, например резервного копирования файлов, обновления ПО, переименования или перемещения файлов, создания отчётов и так далее.
  • Обработка и анализ данных в текстовых файлах, в том числе фильтрация, сортировка, поиск и изменение. Это может быть удобно при обработке лог-файлов или файлов формата CSV.
  • Запуск ping-тестов для проверки работоспособности сайтов и мониторинга производительности серверов.
  • Управление системными ресурсами, мониторинг процессов, очистка временных файлов или логов, определение использования памяти или диска и так далее.
  • Создание сценариев установки и настройки программ, изменения конфигурационных файлов и других действий для установки ПО на новой системе.
  • Работа с файловой системой: создание, копирование, перемещение, переименование или удаление файлов и папок, проверка существования файлов, редактирование прав доступа.
  • Вызов внешних команд, например системных, других скриптов или программ.

Смысл скриптов в том, что мы один раз пишем нужную последовательность команд, сохраняем её в файл, а потом вызываем этот файл — и вся последовательность выполняется автоматически. При этом скрипт может быть как на 5, так и на 500 строк — компьютеру неважен размер, он в любом случае выполнит все команды по очереди. А ещё скрипты можно вызывать из других скриптов и так создавать целые конвейеры по выполнению нужных задач на компьютере. 

Как начать работать с Bash

Чаще всего с помощью bash-скрипты работают с серверами, где нет интерфейсов, а есть только командная строка. Но использовать такие скрипты можно и на обычном компьютере.

Большинство дистрибутивов Linux и Unix-подобных систем поставляется с установленной по умолчанию оболочкой Bash. Например, если у вас операционная система mac OS, для начала работы с Bash достаточно запустить программу «Терминал».

В mac OS Catalina оболочку по умолчанию сменили на Zsh. Чтобы сменить её на bash, нужно открыть настройки терминала и указать полный путь: /bin/bash.

Как начать работать с Bash

После этого нужно перезагрузить терминал, и оболочка сменится на bash:

Как начать работать с Bash

Проверить тип оболочки в терминале можно командой ps

Как создавать bash-скрипты

Писать bash-скрипты можно как в текстовом редакторе, например блокноте, так и в терминале. В первом случае файл со скриптом нужно будет сохранить с расширением .sh, во втором — создать файл с помощью команды nano имя_скрипта.sh. Sh — это сокращение от Shell.

Любой bash-скрипт начинается с такой строки:

#!/bin/bash

Это позволит системе использовать Bash для выполнения.

Создадим самый простой скрипт с приветствием:

#!/bin/bash
echo "Привет, это журнал Код!"

Теперь достаточно сохранить файл и предоставить ему разрешение на выполнение с помощью такой команды:

chmod +x имя_скрипта.sh

Чтобы запустить скрипт, нужно использовать команду:

./имя_скрипта.sh

Рассмотрим чуть более сложный скрипт. Например, нам нужно проверить, сколько места осталось на сервере для почты. Такой скрипт сделает проверку и, если сервер заполнен на 90%, пришлёт email с уведомлением:

#!/bin/sh
# адрес получателя уведомления
EMAIL_TO="адрес_электронной почты"
# адрес, с которого будет отправлено уведомление
EMAIL_FROM="адрес_электронной_почты"
# пороговое значение свободного места на диске в процентах
THRESHOLD=90
# получаем информацию о свободном месте на диске, фильтруем вывод, выбираем нужные поля, сохраняем результаты в переменную output
df -PH | grep -vE '^Filesystem|tmpfs|cdrom|none' | awk '{ print $5 " " $1 }' | while read output;
# цикл проверки
do
  # содержимое переменной output
  echo $output
  # выбираем процент использования свободного места на диске из переменной output, удаляем символ процента, сохраняем результат в переменную usep
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1  )
  # выбираем имя раздела из переменной output, сохраняем результат в переменную partition
  partition=$(echo $output | awk '{ print $2 }' )
  # сравниваем значения usep и THRESHOLD (больше или равно)
  if [ $usep -ge $THRESHOLD ]; then
    # уведомление (ubuntu)
    echo "Осталось мало места \"$partition ($usep%)\" на сервере $(hostname) на дату $(date)" | mail -s "Внимание: на диске осталось мало места $usep%" $EMAIL_TO -aFrom:$EMAIL_FROM
    # уведомление (centos)
    #echo "Осталось мало места \"$partition ($usep%)\" на сервере $(hostname) на дату $(date)" | mail -s "Внимание: на диске осталось мало места $usep%" $EMAIL_TO -- -f $EMAIL_FROM
    # прерывание цикла, если условие выполнено
    break
  fi
# конец цикла
done

Bash и Windows

Bash-скрипты предназначены для unix-подобных операционных систем, а для Window существует формат bat-файлов. Так сложилось, потому что Windows изначально разрабатывали как операционную систему с собственным интерфейсом и своими средствами разработки. Поэтому в Windows нет встроенного доступа к unix-командам, таким как bash.

Теоретически в Windows можно использовать bash-скрипты с помощью виртуальной машины или эмулятора. Например, воспользоваться подсистемой Windows Subsystem for Linux (WSL), чтобы установить дистрибутив Linux из Microsoft Store по поиску «Ubuntu» или «Debian». После установки Bash будет доступен из меню «Пуск».

Но всё-таки bash-скрипты в Windows менее эффективны и удобны, чем bat-файлы — более «родные» для этой ОС. Фактически с их помощью можно делать то же самое, что и с bash-скриптами. Для работы со скриптами в Windows есть удобная оболочка PowerShell — мы уже работали с ней, когда настраивали свой сервер для облачного хранилища или запускали Stable Diffusion у себя на компьютере. На минимальном уровне в Windows можно писать такие же скрипты, как на Linux, но для полноценного администрирования на скриптах этого часто недостаточно.

Интерфейс Windows PowerShell

Интерфейс Windows PowerShell

Что дальше

В следующий раз мы напишем пару полезных скриптов для mac OS, а потом разберём создание подобных скриптов на компьютере с Windows. А заодно посмотрим, как эти две системы отличаются с этой стороны и где удобнее настраивать автоматизацию с помощью командной строки. Подпишитесь, чтобы не пропустить :-)

To run a Bash script on Windows, you can use the Windows Subsystem for Linux (WSL) or Git Bash to execute your script directly from the command line.

Here’s a code snippet to run a Bash script:

bash your_script.sh

Understanding Bash Scripts

What is a Bash Script?

A Bash script is a file that contains a series of commands that the Bash interpreter can execute. These scripts enable you to automate tasks that you would normally perform in the command line interface, making repetitive tasks easier and more efficient. Common use cases for Bash scripts include automating backups, running scheduled tasks, and managing system resources.

The Benefits of Using Bash Scripts

Using Bash scripts has several advantages:

  • Efficiency: By automating repetitive tasks through scripts, you save time and reduce the possibility of human error.
  • Flexibility: Bash scripts can be used in conjunction with various tools and commands available in a Unix-like environment, extending their capabilities.
  • Cross-Platform Nature: Bash scripts can often be run on different operating systems, allowing for more versatile development and deployment options.

Bash Script Options: A Quick Guide to Mastering Choices

Bash Script Options: A Quick Guide to Mastering Choices

Prerequisites for Running Bash Scripts on Windows

Setting Up the Environment

Windows Subsystem for Linux (WSL)

Windows Subsystem for Linux (WSL) enables you to run a Linux distribution alongside your Windows operating system. This allows you to execute Bash scripts natively within a Linux environment. To enable WSL on Windows 10 or 11, follow these steps:

  1. Open PowerShell as Administrator.
  2. Run the command:
wsl --install
  1. Restart your computer.

After installation, you can choose a Linux distribution like Ubuntu from the Microsoft Store.

Installing a Bash Shell

Using Ubuntu / Debian on WSL

Once WSL is enabled, install a Linux distribution from the Microsoft Store. Simply search for «Ubuntu» or «Debian» and click the «Install» button. Upon successful installation, launch the application to complete the setup.

Alternatives

If you prefer not to use WSL, you can opt for Git Bash or Cygwin. Both environments provide a Bash-like experience on Windows.

Run Bash Script: Your Quick-Start Guide to Success

Run Bash Script: Your Quick-Start Guide to Success

Executing Bash Scripts on Windows

Creating a Bash Script

Writing a Bash script begins with a text editor. Here’s how to create a simple Bash script called `hello.sh` that prints «Hello, World!».

#!/bin/bash
echo "Hello, World!"

The first line, known as the shebang (`#!/bin/bash`), indicates which interpreter should be used to run the script.

Running Bash Scripts in WSL

Navigating the Terminal

To run Bash scripts within WSL, you must first open your chosen Linux distribution terminal and navigate to the directory where your script is saved. You can use basic terminal commands such as `cd` (change directory) and `ls` (list files).

Execution Commands

There are two main methods to execute your Bash script in WSL:

  • Basic Execution: You can run the script directly by typing:
bash hello.sh
  • Making it Executable: To run the script without having to prefix it with `bash`, you can make it executable:
chmod +x hello.sh

After this, you can execute it using:

./hello.sh

Running Bash Scripts in Git Bash

Setting Up Git Bash

To use Git Bash, you first need to install Git for Windows. You can find the installer on the [official Git website](https://git-scm.com/download/win). During installation, you can choose the relevant options to set up your Bash environment.

Executing Scripts in Git Bash

Just like in WSL, create the `hello.sh` script in Git Bash. To run the script, you simply navigate to its directory and execute the following command:

bash hello.sh

Running Bash Scripts in Cygwin

Cygwin Setup

Cygwin provides a large collection of GNU and Open Source tools which provide functionality similar to a Linux distribution on Windows. To install Cygwin, navigate to the [Cygwin website](https://www.cygwin.com/) and download the installer. Follow the setup instructions, selecting the packages you wish to install.

Executing Scripts in Cygwin

After creating your Bash script in the Cygwin terminal, the execution process is similar. Use the `bash` command or mark the script as executable before running it.

Run Bash Script on Mac: A Simple Guide

Run Bash Script on Mac: A Simple Guide

Common Issues and Troubleshooting

Handling Script Errors

When running Bash scripts, you may encounter common error messages, such as «command not found» or «permission denied.» These can be addressed through basic troubleshooting steps—ensure that the command is correctly spelled, the script file exists, and you have the necessary permissions.

Performance Issues

If your Bash script runs slowly, investigate any potential bottlenecks, such as infinite loops or redundant function calls. Optimizing your scripts can lead to better performance and faster execution times.

Mastering Bash for Windows: A Quick Guide for Beginners

Mastering Bash for Windows: A Quick Guide for Beginners

Best Practices for Writing and Running Bash Scripts on Windows

Script Organization

For clarity, ensure that your scripts are well-organized. Use comments to document sections of code and explain the purpose of specific commands. This practice not only benefits you but also helps anyone else who may need to use or modify your scripts in the future.

Testing Scripts

Before deploying any scripts, it’s essential to test them thoroughly. Run your scripts in a safe environment and use tools like ShellCheck to check for syntax errors and coding best practices.

Bash Script Closure: Quick Guide to Mastering It

Bash Script Closure: Quick Guide to Mastering It

Conclusion

Being able to run Bash scripts on Windows significantly enhances your productivity and allows you to harness the power of automation. By following the steps outlined above, you can easily set up your environment, write and execute Bash scripts effectively. The combination of WSL, Git Bash, and Cygwin provides robust options for integrating Bash into your workflow.

Bash Script Beginner: Your Quick Start to Shell Mastery

Bash Script Beginner: Your Quick Start to Shell Mastery

Further Reading and Resources

For those looking to deepen their knowledge, check out recommended books, websites, and forums for Bash scripting. Explore tutorials and resources on WSL, Git Bash, and Cygwin to continue your journey into the world of Bash scripting.

Running a Bash script in Windows might seem daunting at first, especially if you’re accustomed to using different operating systems. However, with the right tools and guidance, you can easily execute your Bash scripts on a Windows environment. In this article, we will explore various methods to run Bash scripts on Windows, optimizing for those curious about run bash script windows. Let’s dive right in!

What is a Bash Script?

Bash scripts are files containing a series of commands executed in the Bash shell, which is a Unix-based command-line interface. These scripts are widely used in Linux systems for automating tasks, managing system operations, and leveraging powerful features available in the Bash environment. The flexibility of Bash scripts allows for executing complex tasks with simple instructions.

Why Use Bash Scripts on Windows?

Although Windows has its own scripting capabilities via PowerShell and batch files, many developers and system administrators prefer Bash for various reasons:

  • Familiarity: Many experienced developers utilize Linux or Unix systems
  • Compatibility: Bash scripts can often be ported between platforms with minimal modifications
  • Rich toolset: Bash has a broad suite of built-in commands and third-party tools

Ways to Run Bash Scripts on Windows

There are several methods to run Bash scripts on Windows, each suited to different user preferences and requirements:

1. Using Windows Subsystem for Linux (WSL)

Windows Subsystem for Linux (WSL) allows you to run a Linux distribution alongside your Windows operating system. This is one of the most popular methods for running Bash scripts on Windows.

Steps to Enable WSL:

  1. Open the Windows PowerShell as an administrator.
  2. Run the command:
    wsl --install
  3. Restart your computer to apply the changes.

Downloading a Linux Distribution:

After enabling WSL, you can choose a Linux distribution from the Microsoft Store (e.g., Ubuntu, Debian). Once installed, you can open it just like any other application.

Running Your Bash Script:

  1. Open your chosen Linux distribution from the Start menu.
  2. Navigate to the directory containing your script using the cd command.
  3. To run the Bash script, use:
bash script_name.sh

2. Using Git Bash

Git Bash is a package that installs a Bash emulation environment on Windows, which is particularly helpful for Git version control. Here’s how to install and use Git Bash:

Installing Git Bash:

  1. Download the Git installer from the Git Official Site.
  2. Run the installer and follow the prompts to complete the installation.

Running Your Script in Git Bash:

  1. Open Git Bash from the Start menu.
  2. Use the cd command to navigate to your script’s directory.
  3. Execute the Bash script with:
bash script_name.sh

3. Using Cygwin

Cygwin provides a large collection of GNU and Open Source tools which provide functionality similar to a Linux distribution on Windows. Follow these steps to install and use it:

Installing Cygwin:

  1. Download the Cygwin setup executable from the Cygwin website.
  2. Run the installer and select the packages needed for your Bash scripts.

Running Your Script with Cygwin:

  1. Launch Cygwin from the Start menu.
  2. Change to your script’s directory using the cd command.
  3. Run your script:
bash script_name.sh

Best Practices for Writing Bash Scripts

When creating Bash scripts to run on Windows or any platform, consider the following best practices to enhance readability and functionality:

  • Use Descriptive Names: Name your scripts descriptively to reflect their purpose.
  • Document Your Code: Comment your script to explain complex parts or functions.
  • Make Your Script Executable: Use the command:
chmod +x script_name.sh

Test Thoroughly: Always test your scripts in a controlled environment before deploying them.

Common Issues and Troubleshooting

Despite the simplicity of running Bash scripts on Windows, you may encounter some common issues:

1. Permission Denied Error

This error occurs when your script lacks execution privileges. Ensure you have made the script executable using the chmod command as mentioned above.

2. Line Endings Issues

Bash scripts created in Windows can have different line endings than those in Linux. To convert line endings, use:

dos2unix script_name.sh

3. Environment Variable Problems

If your script relies on certain environment variables, ensure they’re set correctly within your Bash environment. You can check your environment variables with:

printenv

Conclusion

Running a Bash script on Windows has become increasingly accessible with the introduction of tools like WSL, Git Bash, and Cygwin. Each method has its advantages, so choose the one that best fits your workflow and requirements. Always keep usability and compatibility in mind, as well as best practices for writing effective and efficient Bash scripts.

With this guide, you’re now equipped with the knowledge to run bash scripts on Windows. Enjoy automating your tasks and enhancing your productivity! For more tips and tutorials, feel free to check our other articles using hashtags: #BashScripting #Windows #ScriptingTutorials #TechTips #Automation.

  • 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:

  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
  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!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Центр сертификации microsoft windows
  • Как раздать интернет с компьютера через wifi адаптер windows 10
  • Nemo не видит сеть windows
  • Windows 2000 professional 1 2cpu
  • Просмотр подключенных usb устройств windows