Bash command line for windows

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

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

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

Для пользователя 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 for Windows allows users to run Bash commands natively in a Windows environment, enabling efficient script execution and system management.

Here’s an example of how to list all files in a directory:

ls -la

Getting Started with Bash on Windows

What is Bash?

Bash, which stands for «Bourne Again SHell,» is a Unix shell and command language that interprets and executes commands from the user or from a script. It is widely used in many Linux distributions, and it brings powerful scripting capabilities and command line utilities that facilitate tasks ranging from file manipulation to system monitoring. Utilizing Bash on Windows opens a world of commands and tools that enhance productivity and efficiency in a familiar environment.

Installing Bash on Windows

To use Bash on Windows, you typically have two main installation routes:

Windows Subsystem for Linux (WSL)
WSL allows you to run a full-fledged Bash shell integrated with the Windows operating system. This is the preferred method for most users needing a close-to-native Linux experience.

Git Bash
This is a package that provides a Bash emulation for Windows. It is lighter than WSL and is specifically tailored for users who want to handle Git repositories using bash commands.

Detailed Steps for Installing WSL

  1. Enable WSL:

    • Open PowerShell as an Administrator and run:
      wsl --install
      
    • This command installs the Ubuntu distribution by default.
  2. Restart your computer: Your system will prompt you to restart.

  3. Complete the installation: After rebooting, open the newly installed Ubuntu from the Start menu, where you’ll be guided to set up your username and password.

Detailed Steps for Installing Git Bash

  1. Download Git for Windows: Visit the [official Git website](https://git-scm.com/download/win) and download the installer.

  2. Run the installer: Follow the on-screen instructions. You can select options to integrate Git Bash with the Windows context menu, allowing you to open a bash terminal from any folder.

  3. Open Git Bash: After installation, you can find Git Bash in the Start menu or by right-clicking a folder in Explorer.

Mastering Bash on Windows 11: Your Quick Start Guide

Mastering Bash on Windows 11: Your Quick Start Guide

Exploring the Bash Terminal for Windows

Overview of the Bash Shell for Windows

The Bash terminal for Windows provides a command-line interface wherein you can type commands, run scripts, and manage files—all within a robust Unix-like environment. Unlike Command Prompt or PowerShell, Bash offers a different set of commands, encapsulating capabilities that are built around Unix philosophy.

Navigating the Bash Terminal

Navigation in the Bash terminal is straightforward and intuitive. Here are some essential commands you will need:

  • Print Working Directory: To see your current directory, use:

    pwd
    
  • List Files: View the contents of your directory using:

    ls
    
  • Change Directory: Navigate to a different directory with:

    cd directoryname
    

    You can go back to the previous directory with:

    cd ..
    

Manipulating Files and Directories in Bash

File Management Commands

Managing files and directories is a core function when using Bash on Windows.

  • Create a New File: You can create a new file with:

    touch filename
    
  • Create a New Directory: To create a directory, use:

    mkdir directoryname
    
  • Remove a File: To delete a file, type:

    rm filename
    
  • Remove a Directory: To delete a directory (ensure it’s empty), use:

    rmdir directoryname
    

Copying and Moving Files

Once you’re comfortable with file creation and deletion, you will often need to copy or move files.

  • Copy a File: To duplicate a file, use:

    cp sourcefile destinationfile
    
  • Move a File: Move files around your directories with:

    mv filename target_directory
    

These commands are incredibly useful for quickly managing files without the need for a graphical interface.

bash For In List: Quick Guide to Iteration in Bash

bash For In List: Quick Guide to Iteration in Bash

Advanced Bash Commands for Windows Users

Scripting in Bash

Bash scripting is a powerful way to automate tasks. Here’s how to create a simple script:

  1. Open a text editor of your choice via Bash (like `nano` or `vim`).
  2. Type the following lines to create a script that prints «Hello, World!»:
    #!/bin/bash
    echo "Hello, World!"
    
  3. Save the file as `hello.sh` and make it executable:
    chmod +x hello.sh
    
  4. Run your script:
    ./hello.sh
    

Environment Variables in Bash

Environment variables are dynamic values that affect the behavior of processes on your system.

  • View Environment Variables: To check current environment variables, use:

    printenv
    
  • Set a New Environment Variable:

    export VARIABLE_NAME=value
    

For example, to set a variable called `MY_VAR`:

export MY_VAR="Hello, Bash!"

You can then access this variable later in your scripts or commands.

Mastering Bash for Linux: Quick Command Essentials

Mastering Bash for Linux: Quick Command Essentials

Troubleshooting Common Issues with Bash on Windows

Connectivity Issues

When using WSL, you may occasionally face network-related errors. To resolve these:

  • Check your network settings to ensure WSL is allowed access.
  • Restart the LxssManager service:
    Get-Service LxssManager | Restart-Service
    

Performance Issues

If you find that WSL is running slowly:

  • Increase your allocated resources in `.wslconfig` by setting memory limits, for example:

    [wsl2]
    memory=4GB
    
  • Upgrade to WSL 2, which offers improved performance compared to WSL 1.

Mastering Bash Find: Your Guide to Effective File Searches

Mastering Bash Find: Your Guide to Effective File Searches

Conclusion

Using Bash for Windows allows you to leverage the robust capabilities of Unix-like commands directly in your Windows environment. As you explore Bash, make it a habit to practice frequently and explore the deep resources available for learning.

Bash Download: Mastering File Retrieval in Bash

Bash Download: Mastering File Retrieval in Bash

FAQs

Can I run Bash natively on Windows?

Yes, WSL allows you to run Bash natively on your Windows system, providing access to a Ubuntu-like terminal environment.

Is Bash on Windows different from Linux Bash?

While the core functionality remains the same, there are slight differences in file systems and package management. However, most standard Bash commands are identical.

What are some powerful Bash commands to know?

Master essential commands such as `grep` for searching through files, `awk` for pattern scanning and processing, and `sed` for stream editing, as they greatly enhance your scripting capabilities.

Mastering the Bash for Loop: a Quick Guide

Mastering the Bash for Loop: a Quick Guide

Call to Action

To delve deeper into the world of Bash, subscribe to our newsletter for more tutorials and feel free to share your experiences and tips about using Bash on Windows!

Warp Terminal

If you are learning Shell scripting probably as a part of your course curriculum, you need to use Linux commands to practice the commands and scripting.

Your school lab might have Linux installed but you don’t have a Linux laptop but a regular Windows computer like everyone else. Your homework needs to run Linux commands and you wonder how to run Bash commands and scripts on Windows.

You can install Linux alongside Windows in dual boot mode. This method allows you to choose either Linux or Windows when you start your computer. But taking all the trouble to mess with partitions for the sole purpose of running Linux commands may not be for everyone.

You can also use Linux terminals online but your work won’t be saved here.

The good news is that there are several ways you can run Linux commands inside Windows, like any regular application. Isn’t it cool?

Using Linux commands inside Windows

Run Linux Commands In Windows

As an ardent Linux user and promoter, I would like to see more and more people using ‘real’ Linux but I understand that at times, that’s not the priority. If you are just looking to practice Linux to pass your exams, you can use one method to run Bash commands on Windows.

1. Use Linux Bash Shell on Windows 10 with WSL

Did you know that you can run a Linux distribution inside Windows 10? The Windows Subsystem for Linux (WSL) allows you to run Linux inside Windows. The upcoming version of WSL will be using the real Linux kernel inside Windows.

This WSL, also called Bash on Windows, gives you a Linux distribution in command-line mode running as a regular Windows application. Don’t be scared with the command line mode because your purpose is to run Linux commands. That’s all you need.

Using Bash on Windows 10

Ubuntu Linux inside Windows

You can find some popular Linux distributions like Ubuntu, Kali Linux, openSUSE etc in Windows Store. You just have to download and install it like any other Windows application. Once installed, you can run all the Linux commands you want.

Install Windows Subsyetm for Linux

Linux distributions in Windows 10 Store

Please refer to this tutorial about installing Linux bash shell on Windows.

How to Install Linux Bash Shell on Windows [Step-by-Step Guide]

Step-by-step screenshot guide to show you how to install bash on Windows 11 and 10.

It’s FOSSAbhishek Prakash

2. Use Git Bash to run Bash commands on Windows

You probably know what Git is. It’s a version control system developed by Linux creator Linus Torvalds.

Git for Windows is a set of tools that allows you to use Git in both command line and graphical interfaces. One of the tools included in Git for Windows is Git Bash.

Git Bash application provides and emulation layer for Git command line. Apart from Git commands, Git Bash also supports many Bash utilities such as ssh, scp, cat, find etc.

Git Bash

Git Bash

In other words, you can run many common Linux/Bash commands using the Git Bash application.

You can install Git Bash in Windows by downloading and installing the Git for Windows tool for free from its website.

3. Using Linux commands in Windows with Cygwin

If you want to run Linux commands in Windows, Cygwin is a recommended tool. Cygwin was created in 1995 to provide a POSIX-compatible environment that runs natively on Windows. Cygwin is a free and open source software maintained by Red Hat employees and many other volunteers.

For two decades, Windows users use Cygwin for running and practicing Linux/Bash commands. Even I used Cygwin to learn Linux commands more than a decade ago.

Cygwin Shell

Cygwin | Image Credit

You can download Cygwin from its official website below. I also advise you to refer to this Cygwin cheat sheet to get started with it.

4. Use Linux in a virtual machine

Another way is to use virtualization software and install Linux in it. This way, you install a Linux distribution (with a graphical interface) inside Windows and run it like a regular Windows application.

This method requires that your system has a good amount of RAM, at least 4 GB but better if you have over 8 GB of RAM. The good thing here is that you get the real feel of using a desktop Linux. If you like the interface, you may later decide to switch to Linux completely.

Ubuntu Running In Virtual Machine Inside Windows

Ubuntu Running in Virtual Machine Inside Windows

There are two popular tools for creating virtual machines on Windows, Oracle VirtualBox and VMware Workstation Player. You can use either of the two. Personally, I prefer VirtualBox.

You can follow this tutorial to learn how to install Linux in VirtualBox.

Install Linux Inside Windows Using VirtualBox [Step by Step Guide]

Brief: Using Linux in a virtual machine gives you the option to try Linux within Windows. This step-by-step guide shows you how to install Linux inside Windows using VirtualBox. There are several ways to install Linux. You can clean everything from your system and install Linux. You can dual bo…

It’s FOSSAbhishek Prakash

Conclusion

The best way to run Linux commands is to use Linux. When installing Linux is not an option, these tools allow you to run Linux commands on Windows. Give them a try and see which method is best suited for you.

About the author

Abhishek Prakash

Created It’s FOSS 11 years ago to share my Linux adventures. Have a Master’s degree in Engineering and years of IT industry experience. Huge fan of Agatha Christie detective mysteries 🕵️‍♂️

63

63 people found this article helpful

How to Run the Bash Command Line in Windows 10

Windows + Linux = ❤

Updated on August 17, 2022

What to Know

  • Activate WSL as an optional Windows feature or through a PowerShell command > reboot.
  • Next, go to the Windows Store > select and install a distribution.
  • Run the distribution and update if needed. Use it to run bash scripts or Linux command line utilities.

This article explains how to activate, download, install and use the Windows Subsystem for Linux (WSL) in Windows 10.

How to Run WSL in Windows

In the Windows 10 Anniversary Update, Microsoft added the Windows Subsystem for Linux to Windows 10 and even offered (in partnership with Canonical) a fully functional version of Ubuntu Linux—officially, just shell access, although it took about three nanoseconds for people to figure out how to run regular Linux apps in X sessions on Windows 10.

The Microsoft Store offers officially supported Linux distributions for Ubuntu, openSUSE Leap, SUSE Linux Enterprise, Debian/GNU Linux, and Kali Linux. Each of these distributions offers command-line access to Linux, from which you can run bash scripts or Linux command-line utilities.

By default, you cannot use WSL. Instead, you must activate WSL as an optional Windows feature. Either open the Windows Features wizard and check the box or open a PowerShell prompt as administrator and execute:

 Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

Reboot after you activate WSL.

Install a Distribution

Launch the Windows Store and select a distribution to install.

Run the Distribution for the First Time

After the distribution is loaded onto your computer through Windows Store, run it. You’ll have to create a new user account just as if you had installed the distribution as a stand-alone operating system on a fresh hard drive.

Upgrading Your Installation

Your Linux distribution isn’t a pretend environment—it’s an actual Linux system that uses WSL instead of a standard kernel image. So you’ll need to attend to normal Linux housekeeping.

Start with updating the distribution according to the system’s architecture. For example, Debian and Ubuntu use apt.

Using A Command Line Program

After you’ve properly updated the distribution, you’re free to run whatever programs you wish—including shell scripts and command-line utilities.

For example, you can execute the top command to check out system performance.

Technically, you cannot run Linux programs that require an X server, although the internet is littered with fairly straightforward workarounds to get Windows 10 to display an X window.

What’s Under the Hood?

When you install a Linux distribution on Windows 10 you aren’t getting a virtual machine or a program that does its best to pretend to be «Bash in Linux.» It’s actually a Linux distribution running normally on your PC thanks to the Windows Subsystem for Linux. The WSL is the «secret sauce» that allows Linux software to run on Windows. In essence, WSL replaces the Linux kernel; Linux works fully as intended, it’s just using WSL rather than a regular Linux kernel image.

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Subscribe

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

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

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

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

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

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

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

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

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

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

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

wsl —set-default-version 2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

C:\cygwin64\bin

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

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

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

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

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

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows 10 lockscreen changer
  • Как сделать кусок скрина на windows 11
  • Microsoft office 2013 download windows 10
  • Как называется телефон с windows
  • Dungeon siege legends of aranna windows 10