- 4 Ways to Run Linux Commands in Windows
- Using Linux commands inside Windows
- 1. Use Linux Bash Shell on Windows 10
- 2. Use Git Bash to run Bash commands on Windows
- 3. Using Linux commands in Windows with Cygwin
- 4. Use Linux in virtual machine
- Integrate Linux Commands into Windows with PowerShell and the Windows Subsystem for Linux
- PowerShell Function Wrappers
- Default Parameters
- Argument Completion
- Conclusion
- System administrator
4 Ways to Run Linux Commands in Windows
Last updated October 29, 2020 By Abhishek Prakash 16 Comments
Brief: Want to use Linux commands but don’t want to leave Windows? Here are several ways to run Linux bash commands in Windows.
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 personally you don’t have a Linux laptop but the 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 command 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
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 of these methods for running Bash commands on Windows.
1. Use Linux Bash Shell on Windows 10
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.
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.
Linux distributions in Windows 10 Store
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.
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.
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 virtual machine
Another way is to use a virtualization software and install Linux in it. This way, you install a Linux distribution (with 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.
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.
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.
Like what you read? Please share it with others.
Integrate Linux Commands into Windows with PowerShell and the Windows Subsystem for Linux
September 26th, 2019
A common question Windows developers have is “why doesn’t Windows have yet?”. Whether longing for a powerful pager like less or wanting to use familiar commands like grep or sed , Windows developers desire easy access to these commands as part of their core workflow.
The Windows Subsystem for Linux (WSL) was a huge step forward here, enabling developers to call through to Linux commands from Windows by proxying them through wsl.exe (e.g. wsl ls ). While a significant improvement, the experience is lacking in several ways:
- Prefixing commands with wsl is tedious and unnatural
- Windows paths passed as arguments don’t often resolve due to backslashes being interpreted as escape characters rather than directory separators
- Windows paths passed as arguments don’t often resolve due to not being translated to the appropriate mount point within WSL
- Default parameters defined in WSL login profiles with aliases and environment variables aren’t honored
- Linux path completion is not supported
- Command completion is not supported
- Argument completion is not supported
The result of these shortcomings is that Linux commands feel like second-class citizens to Windows and are harder to use than they should be. For a command to feel like a native Windows command, we’ll need to address these issues.
PowerShell Function Wrappers
We can remove the need to prefix commands with wsl , handle the translation of Windows paths to WSL paths, and support command completion with PowerShell function wrappers. The basic requirements of the wrappers are:
- There should be one function wrapper per Linux command with the same name as the command
- The wrapper should recognize Windows paths passed as arguments and translate them to WSL paths
- The wrapper should invoke wsl with the corresponding Linux command, piping in any pipeline input and passing on any command line arguments passed to the function
Since this template can be applied to any command, we can abstract the definition of these wrappers and generate them dynamically from a list of commands to import.
The $command list defines the commands to import. Then we dynamically generate the function wrapper for each using the Invoke-Expression command (first removing any aliases that would conflict with the function).
The function loops through the command line arguments, identifies Windows paths using the Split-Path and Test-Path commands, then converts those paths to WSL paths. We run the paths through a helper function we’ll define later called Format-WslArgument that escapes special characters like spaces and parentheses that would otherwise be misinterpreted.
Finally, we pass on pipeline input and any command line arguments through to wsl .
With these function wrappers in place, we can now call our favorite Linux commands in a more natural way without having to prefix them with wsl or worry about how Windows paths are translated to WSL paths:
- man bash
- less -i $profile.CurrentUserAllHosts
- ls -Al C:\Windows\ | less
- grep -Ein error *.log
- tail -f *.log
A starter set of commands is shown here, but you can generate a wrapper for any Linux command simply by adding it to the list. If you add this code to your PowerShell profile, these commands will be available to you in every PowerShell session just like native commands!
Default Parameters
It is common in Linux to define aliases and/or environment variables within login profiles to set default parameters for commands you use frequently (e.g. alias ls=ls -AFh or export LESS=-i ). One of the drawbacks of proxying through a non-interactive shell via wsl.exe is that login profiles are not loaded, so these default parameters are not available (i.e. ls within WSL and wsl ls would behave differently with the alias defined above).
PowerShell provides $PSDefaultParameterValues , a standard mechanism to define default parameter values, but only for cmdlets and advanced functions. Turning our function wrappers into advanced functions is possible but introduces complications (e.g. PowerShell matches partial parameter names (like matching -a for -ArgumentList ) which will conflict with Linux commands that accept the partial names as arguments), and the syntax for defining default values would be less than ideal for this scenario (requiring the name of a parameter in the key for defining the default arguments as opposed to just the command name).
With a small change to our function wrappers, we can introduce a model similar to $PSDefaultParameterValues and enable default parameters for Linux commands!
By passing $WslDefaultParameterValues down into the command line we send through wsl.exe , you can now add statements like below to your PowerShell profile to configure default parameters!
Since this is modeled after $PSDefaultParameterValues , you can temporarily disable them easily by setting the «Disabled» key to $true . A separate hash table has the additional benefit of being able to disable $WslDefaultParameterValues separately from $PSDefaultParameterValues .
Argument Completion
PowerShell allows you to register argument completers with the Register-ArgumentCompleter command. Bash has powerful programmable completion facilities. WSL lets you call into bash from PowerShell. If we can register argument completers for our PowerShell function wrappers and call through to bash to generate the completions, we can get rich argument completion with the same fidelity as within bash itself!
The code is a bit dense without an understanding of some bash internals, but basically:
- We register the argument completer for all of our function wrappers by passing the $commands list to the -CommandName parameter of Register-ArgumentCompleter
- We map each command to the shell function bash uses to complete for it ( $F which is named after complete -F used to define completion specs in bash)
- We convert PowerShell’s $wordToComplete , $commandAst , and $cursorPosition arguments into the format expected by bash completion functions per the bash programmable completion spec
- We build a command line that we can pass to wsl.exe that ensures the completion environment is set up correctly, invokes the appropriate completion function, then outputs a string containing the completion results separated by new lines
- We then invoke wsl with the command line, split the output string on the new line separator, then generate CompletionResults for each, sorting them, and escaping characters like spaces and parentheses that would otherwise be misinterpreted
The end result of this is now our Linux command wrappers will use the exact same completion that bash uses! For example:
Each completion will provide values specific to the argument before it, reading in configuration data like known hosts from within WSL!
will cycle through options. will show all available options.
Additionally, since bash completion is now in charge, you can resolve Linux paths directly within PowerShell!
In cases where bash completion doesn’t return any results, PowerShell falls back to its default completion which will resolve Windows paths, effectively enabling you to resolve both Linux paths and Windows paths at will.
Conclusion
With PowerShell and WSL, we can integrate Linux commands into Windows just as if they were native applications. No need to hunt around for Win32 builds of Linux utilities or be forced to interrupt your workflow to drop into a Linux shell. Just install WSL, set up your PowerShell profile, and list the commands you want to import! The rich argument completion shown here of both command options and Linux and Windows file paths is an experience even native Windows commands don’t provide today.
The complete source code described above as well as additional guidance for incorporating it into your workflow is available at https://github.com/mikebattista/PowerShell-WSL-Interop.
Which Linux commands do you find most useful? What other parts of your developer workflow do you find lacking on Windows?
Let us know in the comments below or over on GitHub!
System administrator
Большинство UNIX-like систем обладают встроенной справкой, которая подробно описывает все доступные команды. Однако чтобы воспользоваться этой справкой, вы должны знать, по крайней мере, название команды, о которой вы хотите получить информацию. Поскольку большинство пользователей только в общих чертах понимают, что они хотят сделать, то, как правило, встроенная справка мало полезна новичкам.
Этот справочник поможет пользователям, знающим, что они хотят сделать, найти соответствующую команду Linux по краткому описанию.
Системная информация: arch или uname -m — отобразить архитектуру компьютера uname -r — отобразить используемую версию ядра dmidecode -q — показать аппаратные системные компоненты — (SMBIOS / DMI) hdparm -i /dev/hda — вывести характеристики жесткого диска hdparm -tT /dev/sda — протестировать производительность чтения данных с жесткого диска cat /proc/cpuinfo — отобразить информацию о процессоре cat /proc/interrupts — показать прерывания cat /proc/meminfo — проверить использование памяти cat /proc/swaps — показать файл(ы) подкачки cat /proc/version — вывести версию ядра cat /proc/net/dev — показать сетевые интерфейсы и статистику по ним cat /proc/mounts — отобразить смонтированные файловые системы lspci -tv — показать в виде дерева PCI устройства lsusb -tv — показать в виде дерева USB устройства date — вывести системную дату cal 2007 — вывести таблицу-календарь 2007-го года date 041217002007.00* — установить системные дату и время ММДДЧЧммГГГГ.СС (МесяцДеньЧасМинутыГод.Секунды) clock -w — сохранить системное время в BIOS Остановка системы: shutdown -h now или init 0 или telinit 0 — остановить систему shutdown -h hours:minutes & — запланировать остановку системы на указанное время shutdown -c — отменить запланированную по расписанию остановку системы shutdown -r now или reboot — перегрузить систему logout — выйти из системы Файлы и директории: cd /home — перейти в директорию ‘/home’ cd .. — перейти в директорию уровнем выше cd ../.. — перейти в директорию двумя уровнями выше cd — перейти в домашнюю директорию cd
user — перейти в домашнюю директорию пользователя user cd — — перейти в директорию, в которой находились до перехода в текущую директорию pwd — показать текущюю директорию ls — отобразить содержимое текущей директории ls -F — отобразить содержимое текущей директории с добавлением к именам символов, храктеризующих тип ls -l — показать детализированое представление файлов и директорий в текущей директории ls -a — показать скрытые файлы и директории в текущей директории ls *4* — показать файлы и директории содержащие в имени цифры tree или lstree — показать дерево файлов и директорий, начиная от корня (/) mkdir dir1 — создать директорию с именем ‘dir1’ mkdir dir1 dir2 — создать две директории одновременно mkdir -p /tmp/dir1/dir2 — создать дерево директорий rm -f file1 — удалить файл с именем ‘file1’ rmdir dir1 — удалить директорию с именем ‘dir1’ rm -rf dir1 — удалить директорию с именем ‘dir1’ и рекурсивно всё её содержимое rm -rf dir1 dir2 — удалить две директории и рекурсивно их содержимое mv dir1 new_dir — переименовать или переместить файл или директорию cp file1 file2 — сопировать файл file1 в файл file2 cp dir/* . — копировать все файлы директории dir в текущую директорию cp -a /tmp/dir1 . — копировать директорию dir1 со всем содержимым в текущую директорию cp -a dir1 dir2 — копировать директорию dir1 в директорию dir2 ln -s file1 lnk1* — создать символическую ссылку на файл или директорию ln file1 lnk1 — создать «жёсткую» (физическую) ссылку на файл или директорию touch -t 0712250000 fileditest — модифицировать дату и время создания файла, при его отсутствии, создать файл с указанными датой и временем (YYMMDDhhmm) Поиск файлов: find / -name file1 — найти файлы и директории с именем file1. Поиск начать с корня (/) find / -user user1 — найти файл и директорию принадлежащие пользователю user1. Поиск начать с корня (/) find /home/user1 -name «*.bin» — найти все файлы и директории, имена которых оканчиваются на ‘. bin’. Поиск начать с ‘/ home/user1’* find /usr/bin -type f -atime +100 — найти все файлы в ‘/usr/bin’, время последнего обращения к которым более 100 дней find /usr/bin -type f -mtime -10 — найти все файлы в ‘/usr/bin’, созданные или изменённые в течении последних 10 дней find / -name *.rpm -exec chmod 755 ‘<>‘ ; — найти все фалы и директории, имена которых оканчиваются на ‘.rpm’, и изменить права доступа к ним find / -xdev -name «*.rpm» — найти все фалы и директории, имена которых оканчиваются на ‘.rpm’, игнорируя съёмные носители, такие как cdrom, floppy и т.п. locate «*.ps» — найти все файлы, сожержащие в имени ‘.ps’. Предварительно рекомендуется выполнить команду ‘updatedb’ whereis halt — показывает размещение бинарных файлов, исходных кодов и руководств, относящихся к файлу ‘halt’ which halt — отображает полный путь к файлу ‘halt’ Монтирование файловых систем: mount /dev/hda2 /mnt/hda2 — монтирует раздел ‘hda2’ в точку монтирования ‘/mnt/hda2’. Убедитесь в наличии директории-точки монтирования ‘/mnt/hda2’ umount /dev/hda2 — размонтирует раздел ‘hda2’. Перед выполнением, покиньте ‘/mnt/hda2’ fuser -km /mnt/hda2 — принудительное размонтирование раздела. Применяется в случае, когда раздел занят каким-либо пользователем umount -n /mnt/hda2 — выполнить размонитрование без занесения информации в /etc/mtab. Полезно когда файл имеет атрибуты «только чтение» или недостаточно места на диске mount /dev/fd0 /mnt/floppy — монтировать флоппи-диск mount /dev/cdrom /mnt/cdrom — монтировать CD или DVD mount /dev/hdc /mnt/cdrecorder — монтировать CD-R/CD-RW или DVD-R/DVD-RW(+-) mount -o loop file.iso /mnt/cdrom — смонтировать ISO-образ mount -t vfat /dev/hda5 /mnt/hda5 — монтировать файловую систему Windows FAT32 mount -t smbfs -o username=user,password=pass //winclient/share /mnt/share — монтировать сетевую файловую систему Windows (SMB/CIFS) mount -o bind /home/user/prg /var/ftp/user — «монтирует» директорию в директорию (binding). Доступна с версии ядра 2.4.0. Полезна, например, для предоставления содержимого пользовательской директории через ftp при работе ftp-сервера в «песочнице» (chroot), когда симлинки сделать невозможно. Выполнение данной команды сделает копию содержимого /home/user/prg в /var/ftp/user Дисковое пространство: df -h — отображает информацию о смонтированных разделах с отображением общего, доступного и используемого пространства (Прим.переводчика. ключ -h работает не во всех *nix системах) ls -lSr |more — выдаёт список файлов и директорий рекурсивно с сортировкой по возрастанию размера и позволяет осуществлять постраничный просмотр du -sh dir1 — подсчитывает и выводит размер, занимаемый директорией ‘dir1’ (Прим.переводчика. ключ -h работает не во всех *nix системах) du -sk * | sort -rn — отображает размер и имена файлов и директорий, с соритровкой по размеру rpm -q -a —qf ‘%10
Дополнение за 18 апреля 2011 года:
Список не является окончательным, описание команд естественно не полное, полное описание команд Вы можете получить в linux shell# man command.
ls : показывает файлы и каталоги в текущей директории, аналог команды dir в Windows.
ls -al : показывает файлы и каталоги в текущей директории, включая подкаталоги, более «сложный» листинг.
cd : сменить директорию, например, если введем команду cd /usr/local/directadmin то перейдем в указанную директорию.
cd
: перейти в домашнюю директорию.
cd — : перейти в директорию в которой находились до перехода в другую директорию.
cd .. : перейти в директорию на 1 уровень вверх.
cat /filename.conf : покажет содержимое файла.
chmod : изменят атрибуты, после команды chmod устанавливается циферное значение, доступ для ПОЛЬЗОВАТЕЛЯ-ГРУППЫ-ВСЕХ:
0 = — Нет доступа
1 = —X Только выполнение
2 = -W- Только запись
3 = -WX Запись и выполнение
4 = R— Только чтение
5 = R-X Чтение и выполнение
6 = RW- Чтение и запись
7 = RWX Чтение, запись и выполнение
Использование:
chmod набор правил filename
chmod 000 : Ни у кого не будет доступа
chmod 644: Обычно используется для HTML страниц
chmod 755: Обычно применяется для CGI скриптов
chown : Изменяет владельца файла или каталога
После команды указывается значение:
ПОЛЬЗОВАТЕЛЬ — ГРУППА
chown root myfile.txt : Установить пользователя root владельцем данного файла.
chown root:root myfile.txt : Изменить пользователя и группу для данного файла и установить root.
tail : аналог команды cat, только читает файлы с конца.
tail /var/log/messages : покажет последние 20 (по умолчанию) строк файла /var/log/messages
tail -f /var/log/messages : выводит листинг файла непрерывно, по мере его обновления.
tail -200 /var/log/messages : выведет на экран последние 200 строк с указанного файла.
more : как cat, только показывает файл поэкранно, а не весь сразу
more /etc/userdomains : Покажет листинг файла на весь экран. Для прокрутки используйте пробел, q для выхода из режима просмотра.
pico : простой в работе редактор с дружественным интерфейсом.
Редактор файлов VI
vi : редактор файлов, много опций, для ноыичка тяжелый в работе.
В редакторе vi Вы можете использовать следующие полезные коменды, только Вы будете должны нажать клавишу SHIFT + :
:q! : Выйти из файла и редактора без сохранения.
:w : Сохранить.
:wq : Сохранить и выйим из редактора.
:номер строки : например :25 : перейти на 25 строку
:$ : Перейти на последнюю строку в файле
:0 : Перейти на первую строку в файле
grep : ищет заданное значение в файлах.
grep root /etc/passwd : ищет значения root в файле /etc/passwd
grep -v root /etc/passwd : покажет все строки где встречается значение root.
ln : создает ссылки между файлами и папками
ln -s /usr/local/apache/conf/httpd.conf /etc/httpd.conf : Теперь Вы можете редактировать /etc/httpd.conf а не оригинал. изменения будут произведены и в оригинале.
last : показывает кто авторизовывался и когда
last -20 : показывает последние 20 авторизаций
w : Показывает кто еще авторизован в шелле и откуда вошли
who : Также показывает кто залогинен в шелл.
netstat : показывает все текущие сетевые подключения.
netstat -an : показывает подключения к серверу, с какого IP на какой порт.
netstat -rn : показывает таблицу IP маршрутизации.
top : показывает все запущенные процессы в таблице, информацию по использованию памяти, uptime системы и другую полезную информацию. Нажав Shift + M увидите таблицу использования памяти или Shift + P таблицу использования процессора.
ps: показывает процесс лист в упрощенном виде.
ps U username : показывает процессы определенного юзера.
ps aux : показывает все системные процессы.
ps aux —forest : показывает все системные процессы, вывод процессов в форме дерева в определенной иерархии.
touch : создает пустой файл.
du : показывает использование жесткого диска.
du -sh : показывает суммарно, в человеко-читаемом формате, общее использование диска, текущей директории и подкаталогов.
du -sh * : тоже самое, но для каждого файла и директории. помогает найти большие файлы, занимающие много места.
wc : счетчик слов
wc -l filename.txt : посчтитает сколько строк находится в файле filename.txt
cp : копировать файл
cp filename filename.backup : скопирует filename в filename.backup
mv : перемещает файлы и папки.
rm : удаляет файл или папку.
rm filename.txt : удаляет filename.txt, при этои спросит действительно ли Вы хотите удалить данный файл.
rm -f filename.txt : удалит filename.txt без подтверждения удаления
rm -rf tmp/ : рекурсивно удаляет каталог tmp, все файлы в нем и подкаталоги.
TAR: упаковка и распаковка .tar.gz и .tar файлов.
tar -zxvf file.tar.gz : распакует архив
tar -xvf file.tar : распакует архив
tar -cf archive.tar contents/ : содержимое каталога contents/ упакует в archive.tar
gzip -d filename.gz : Декомпрессирует и распакует файл.
ZIP Files: распаковывает .zip файлы
unzip file.zip
Firewall — iptables команды
iptables -I INPUT -s IPADDRESSHERE -j DROP : Запретит все соединения с указанного IP
iptables -L : Лист правил iptables
iptables -F : очищает все iptables правила
iptables —save : Сохраняет текущие правила в память на диск
service iptables restart : Перезапустит iptables
Apache Shell Commands:
httpd -v : Покажет дату и время сборки и версию Apache сервера.
httpd -l : Покажет модули Apache
httpd status : будет работать только если mod_status разрешен и покажет страницу с активными подключениями.
service httpd restart : рестартанет Apache web server
MySQL Shell Commands:
mysqladmin processlist : покажет активные mysql соединения и запросы.