Как работать с bash на windows

Уровень сложности
Простой

Время на прочтение
2 мин

Количество просмотров 5.7K

Для пользователя Linux командная строка Windows кажется чем-то непривычным и неудобным. С появлением WSL казалось, что проблема использования Bash решена, но запуск виртуальной машины требует времени, да и пути в WSL отличаются от Windows. Плюс скорость файловых операций на виртуальной машине хуже.

Ещё есть возможность использовать Bash через MSYS2, но мне хотелось найти что-то более компактное и легковесное, а также простое в настройке и установке.

Так как я часто использовал Linux на роутерах, то познакомился с BusyBox, набор UNIX-утилит командной строки, используемой в качестве основного интерфейса во встраиваемых операционных системах. Оказалось, есть версия BusyBox для Windows. В 2020 году появился Windows Terminal, а в нем есть возможность создавать вкладку с запуском конкретной программы.

Пример вкладки Bash

Пример вкладки Bash

Сложив эти два факта, пришла очевидная мысль, использовать BusyBox, содержащий в себе Bash, в Windows Terminal как отдельную консоль.

Список программ входящих в BusyBox

Список программ входящих в BusyBox

Для этого необходимо скачать BusyBox 64, и я, например положил файл в C:/Program Files/Busybox. А дальше создать новый профиль Windows Terminal и поменять его имя на Bash и указать команду для запуска как C:/Program Files/Busybox/busybox64.exe bash

Профиль для Bash

Профиль для Bash

У этого подхода был один минус, при запуске терминала не из конкретной папки, а из ярлыка на рабочем столе или из панели задач.

Запуск терминала из конкретной папки

Запуск терминала из конкретной папки

То адрес рабочей папки был C:/Windows/System32, и если случайно ввести команду удаления или создания файла, то мы портим важную системную папку. Обойти возможно используя аналог .bashrc или /etc/profile или .profile.

Но просто создать файл .profile мало, BusyBox для Windows их не считывает, для этого необходимо добавить путь к этому файлу в  ENV в “Переменные среды”.

Теперь мы можем написать скрипт, который будет настраивать рабочую директорию при запуске консоли.

#!/bin/bash

domain=$(echo $PWD | tr '[:upper:]' '[:lower:]')

if [ $domain = "c:/windows/system32" ]; then
    cd $HOME
fi

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

Мы получили Bash в Windows Terminal с удобной начальной директорией.

Bash has been one of the most well-known feature of Linux distributions, which due to its flexibility as well as ease of usage, made it popular among programmers. The Windows’ operating system’s command line interface, cmd.exe, on the other hand, lacked various capabilities of it’s Linux counterpart.

Microsoft, therefore, in their Anniversary Update, added several features to the Windows 10 OS, with bash being one of them. To install and use it on Windows 10, one need to perform the following steps :

  1. Start -> Settings -> Update&Security. Under the ‘Use Developer Features’, select ‘Developer mode’.

  2. Selecting the developer mode will pop the following alert. Click yes, and let the computer restart.


  3. Go to Control Panel -> Programs and Features -> Turn Windows Features On and Off. In the window that appears, check the ‘Windows Subsystem for Linux’ option, and click OK.

  4. This will trigger an alert asking for the system to be restarted to complete the installation of the required components. After the restart is complete, go to the command prompt, and type ‘bash’. Follow the instructions that appear to install bash from Windows store. After it is installed, it will be required to create a UNIX username. After completing the installation, exit the prompt.
  5. To access the shell, simply type ‘bash’ in the Windows command prompt, and everything is good to go.

  6. Note that bash runs natively on Windows 10, which is different from using emulators like ‘cygwin’ for Windows which enabled GNU tools to run on unsupported Windows environment. Also, Linux subsystem for Windows 10 is only available on the 64-bit version of the OS.

Last Updated :
11 Jul, 2022

Like Article

Save Article

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!

In order to run natively, you will likely need to use Cygwin (which I cannot live without when using Windows). So right off the bat, +1 for Cygwin. Anything else would be uncivilized.

HOWEVER, that being said, I have recently begun using a combination of utilities to easily PORT Bash scripts to Windows so that my anti-Linux coworkers can easily run complex tasks that are better handled by GNU utilities.

I can usually port a Bash script to Batch in a very short time by opening the original script in one pane and writing a Batch file in the other pane. The tools that I use are as follows:

  • UnxUtils (http://sourceforge.net/projects/unxutils/)
  • Bat2Exe (http://bat2exe.net/)

I prefer UnxUtils to GnuWin32 because of the fact that [someone please correct me if I’m wrong] GnuWin utils normally have to be installed, whereas UnxUtils are standalone binaries that just work out-of-the-box.

However, the CoreUtils do not include some familiar *NIX utilities such as cURL, which is also available for Windows (curl.haxx.se/download.html).

I create a folder for the projects, and always SET PATH=. in the .bat file so that no other commands other than the basic CMD shell commands are referenced (as well as the particular UnxUtils required in the project folder for the Batch script to function as expected).

Then I copy the needed CoreUtils .exe files into the project folder and reference them in the .bat file such as «.\curl.exe -s google.com», etc.

The Bat2Exe program is where the magic happens. Once your Batch file is complete and has been tested successfully, launch Bat2Exe.exe, and specify the path to the project folder. Bat2Exe will then create a Windows binary containing all of the files in that specific folder, and will use the first .bat that it comes across to use as the main executable. You can even include a .ico file to use as the icon for the final .exe file that is generated.

I have tried a few of these type of programs, and many of the generated binaries get flagged as malware, but the Bat2Exe version that I referenced works perfectly and the generated .exe files scan completely clean.

The resulting executable can be run interactively by double-clicking, or run from the command line with parameters, etc., just like a regular Batch file, except you will be able to utilize the functionality of many of the tools that you will normally use in Bash.

I realize this is getting quite long, but if I may digress a bit, I have also written a Batch script that I call PortaBashy that my coworkers can launch from a network share that contains a portable Cygwin installation. It then sets the %PATH% variable to the normal *NIX format (/usr/bin:/usr/sbin:/bin:/sbin), etc. and can either launch into the Bash shell itself or launch the more-powerful and pretty MinTTY terminal emulator.

There are always numerous ways to accomplish what you are trying to set out to do; it’s just a matter of combining the right tools for the job, and many times it boils down to personal preference.

С появлением оболочки Bash Windows 10 вы можете теперь создавать и запускать сценарии оболочки Bash в Windows 10. Вы также можете включить команды Bash в командный файл Windows или сценарий PowerShell.

С появлением оболочки Bash Windows 10 вы можете теперь создавать и запускать сценарии оболочки Bash в Windows 10. Вы также можете включить команды Bash в командный файл Windows или сценарий PowerShell.

Даже если вы знаете, что делаете, это не обязательно так просто, как кажется. Windows и UNIX используют разные символы конца строки, а файловая система Windows доступна в другом месте в среде Bash.

Как написать сценарий Bash в Windows 10

При написании сценариев оболочки в Windows помните, что Windows и UNIX-подобные системы, такие как Linux, используют разные символы «конца строки» в текстовых файлах в сценариях оболочки.

Другими словами, это означает, что вы не можете просто написать сценарий оболочки в «Блокноте». Сохраните файл в «Блокноте», и он не будет правильно интерпретироваться Bash. Тем не менее, вы можете использовать более сложные текстовые редакторы, например, Notepad ++ позволяет вам предоставить файл конечных символов UNIX, нажав «Редактировать»> «Преобразование EOL»> «Формат UNIX / OSX».

Однако вам лучше просто написать сценарий оболочки в самой среде Bash. В среде Bash, основанной на Ubuntu, есть как редакторы vi, так и nano. Редактор vi более мощный, но если вы никогда не использовали его раньше, вы можете начать с nano. Это проще в использовании, если вы новичок.

Однако вам лучше просто написать сценарий оболочки в самой среде Bash. В среде Bash, основанной на Ubuntu, есть как редакторы vi, так и nano. Редактор vi более мощный, но если вы никогда не использовали его раньше, вы можете начать с nano. Это проще в использовании, если вы новичок.

Например, чтобы создать скрипт bash в nano, вы выполните следующую команду в bash:

nano ~/myscript.sh

Это откроет текстовый редактор Nano, указанный в файле с именем «myscript.sh» в домашнем каталоге вашей учетной записи пользователя. (Символ «~» представляет ваш домашний каталог, поэтому полный путь: /home/username/myscript.sh.)

Запустите сценарий оболочки с помощью строки:

Запустите сценарий оболочки с помощью строки:

#!/bin/bash

Введите команды, которые вы хотите запустить, каждый из которых находится в отдельной строке. Скрипт будет запускать каждую команду по очереди. Добавьте символ «#» перед строкой, чтобы рассматривать его как «комментарий», что поможет вам и другим людям понять сценарий, но который не запускается как команда. Для получения более совершенных трюков обратитесь к более подробному руководству по сценариям Bash в Linux. Те же методы будут работать в Bash на Ubuntu в Windows.

Обратите внимание: нет возможности запуска программ Windows из среды Bash. Вы ограничены командами и утилитами терминала Linux, так же, как и в обычной Linux-системе.

Например, давайте просто воспользуемся базовым сценарием «hello world» в качестве примера:

#!/bin/bash # set the STRING variable STRING='Hello World!' # print the contents of the variable on screen echo $STRING

Если вы используете текстовый редактор Nano, вы можете сохранить файл, нажав Ctrl + O, а затем Enter. Закройте редактор, нажав Ctrl + X.

Image

Image

Сделайте исполняемый файл сценария, а затем запустите его

Вероятно, вам понадобится сделать исполняемый файл сценария, чтобы вы могли легко запускать его. В Linux это означает, что вам нужно предоставить файлу сценария исполняемое разрешение. Для этого запустите следующую команду в терминале, указав ее на свой скрипт:

chmod +x ~/myscript.sh

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

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

~/myscript.sh

(Если скрипт находится в текущем каталоге, вы можете запустить его с./myscript.sh)

Image

Image

Как работать с файлами Windows в сценарии Bash

Чтобы получить доступ к файлам Windows в сценарии, вам нужно указать их путь в / mnt / c, а не в пути к ним. Например, если вы хотите указать файл C: Users Bob Downloads test.txt, вам нужно указать путь /mnt/c/Users/Bob/Downloads/test.txt. Для получения дополнительной информации обратитесь к нашему руководству по расположению файлов в оболочке Bash Windows 10.

Как включить команды Bash в скрипт Batch или PowerShell

Наконец, если у вас есть существующий командный файл или сценарий PowerShell, в который вы хотите включить команды, вы можете запускать команды Bash напрямую, используя

bash -c

команда.

Например, чтобы запустить команду Linux в окне командной строки или PowerShell, вы можете запустить следующую команду:

bash -c 'command'

Этот трюк позволяет добавлять команды Bash в командные файлы или сценарии PowerShell. Окно оболочки Bash появится, когда запущена команда Bash.

Обновить: Если у вас установлено несколько Linux-сред, вы можете использовать команду wslconfig для выбора среды Linux по умолчанию, используемой при запуске

bash -c

команда.

Image

Image

Чтобы создать ярлык для сценария Bash изнутри Windows, просто создайте ярлык, как обычно. Для цели ярлыка используйте

bash -c

которую мы описали выше, и укажем на созданный вами сценарий Bash.

Например, вы укажете ярлык на»

bash -c '~/myscript.sh'

Msgstr запустить приведенный выше пример скрипта. Вы также можете просто запустить эту команду из окна командной строки или окна PowerShell.

Рекомендуемые:

Как запустить любую команду командной строки с Cortana

Как запустить любую команду командной строки с Cortana

Cortana, возможно, не так популярна, как надеялась Microsoft, но это может быть полезно. Вам больше не нужно быть рядом с компьютером для выполнения задачи; вы можете кричать с другой стороны комнаты. Однако есть некоторые вещи, которые Кортана не может сделать из коробки.

Как запустить графические приложения для настольных компьютеров Linux из командной строки Windows 10

Как запустить графические приложения для настольных компьютеров Linux из командной строки Windows 10

Башня Bash от Windows 10 официально не поддерживает графические настольные приложения Linux. Microsoft заявляет, что эта функция предназначена только для разработчиков, которые хотят запускать утилиты терминалов Linux. Но базовая «Подсистема Windows для Linux» более мощна, чем позволяет Microsoft.

Как запустить Защитник Windows из командной строки

Как запустить Защитник Windows из командной строки

Защитник Windows и Microsoft Security Essentials имеют возможность сканировать, обновлять или запускать другие задачи с помощью командной строки с использованием утилиты MpCmdRun.exe.

Как запустить средство устранения неполадок в Windows 10 из командной строки

Как запустить средство устранения неполадок в Windows 10 из командной строки

Узнайте, как запускать в командной строке MSDT.exe оборудование, аудио, сетевую сеть, Центр обновления Windows, Обслуживание системы, Приложение, Звук и т. Д. Устранение неполадок в Windows 10/8/7.

Параметры командной строки командной строки, переключатели, параметры

Параметры командной строки командной строки, переключатели, параметры

Этот пост рассказывает о контрольном диске командной строки или параметрах chkdsk, переключателях и параметрах в Windows 10/8/7 и о том, как использовать команды chkdsk, такие как chkdsk / r и т. Д.

  • Как работать с vpn windows 10
  • Как работать с avz для windows 7
  • Как работать с visual studio code c на windows
  • Как работать на клавиатуре без мышки на компьютере windows 7
  • Как работать с ventoy для windows