- Linux commands for Windows
- 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
- Windows command to convert Unix line endings?
- 17 Answers 17
- Юниксовые утилиты командной строки для Windows // Unix-like command line utilities for Windows
- Integrated pack
- MD5, SHA1 и SFV
- Заключение
Linux commands for Windows
It’s very common scenario in IT field that people who are familiar with one OS have to learn/work with another OS. I do see many people, who are familiar with Linux commands, looking for their equivalent commands in Windows OS. Below I have attempted to list down the Windows commands for most widely used Linux commands. If I have missed any, please write in the comments section and let me know.
Ls : The Windows equivalent one is dir. ‘Dir‘ has many switches to list files based on different attributes, sort the list on size or date modified etc.
Grep : Findstr is the closet matching one for grep. find is also for searching strings in files, but it does not have many options.
Adduser: We can use net user to manage user accounts.
Useradd: net localgroup can be used to manage user groups. Net group can be used to manage active directory (domain) groups.
Uname : ver command shows Windows OS version. Systeminfo shows lot of hardware and software information.
Ps : The closest matching command is tasklist, though it’s not as feature rich as ps.
Echo : echo. Very much similar to Linux’s echo.
Md : mkdir
rm: Del deletes files whereas rmdir can be used to delete directories.
Du : du can be used to monitor the disk usage. However, this tool is not part of Windows OS. We need to install it separately. See the link for more information.
Df : Net use. We can list the network shares mapped on the computer.
Mount : Net use . Map network share to local drive
Cat : Type print the contents of a text file in the console/command prompt.
Head : there’s no equivalent command I am aware of.
Tail : Tail resource kit tool.
touch: Fsutil can be used to create files of require size.
I will add few more commands to the list soon…If you are searching for some specific command and do not find it here, please let me know.
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.
Windows command to convert Unix line endings?
Is there a Windows command to convert line endings of a file?
We have a test.bat which we need to run to start our server. We use Perforce and we need to have unix line endings in our workspace. For some reason, we are not allowed to change line endings to Windows in our workspaces. However, the server runs on Windows.
Everytime I have to run the bat file, I open it in Notepad++ and choose Edit→EOL conversion→Windows. Is there a way to automate this so that we won’t need to manually change the line endings everytime we sync with Perforce?
Thanks in advance.
17 Answers 17
This can actually be done very easily using the more command which is included in Windows NT and later. To convert input_filename which contains UNIX EOL (End Of Line) \n to output_filename which contains Windows EOL \r\n , just do this:
The more command has additional formatting options that you may not be aware of. Run more/? to learn what else more can do.
Use unix2dos utility. You can download binaries here.
I was dealing with CRLF issues so I decided to build really simple tool for conversion (in NodeJS):
So if you have NodeJS with npm installed you can try it:
Path might be configured dynamically by using Glob regex (same regex as in shell).
So if you can use NodeJS, it’s really simple and you can integrate this command to convert whole workspace to desired line endings.
You can do this without additional tools in VBScript:
Put the above lines in a file unix2dos.vbs and run it like this:
You can also do it in PowerShell:
which could be further simplified to this:
The above statement works without an explicit replacement, because Get-Content implicitly splits input files at any kind of linebreak (CR, LF, and CR-LF), and Set-Content joins the input array with Windows linebreaks (CR-LF) before writing it to a file.
Windows’ MORE is not reliable, it destroys TABs inevitably and adds lines.
unix2dos is part also of MinGW/MSYS, Cygutils, GnuWin32 and other unix binary port collections — and may already be installed.
When python is there, this one-liner converts any line endings to current platform — on any platform:
Or put the one-liner into a .bat / shell script and on the PATH according to your platform:
and use that tool like
Building on TampaHaze’s and MD XF’s helpful answers.
This will change all .txt files in place in the current directory from from LF to CRLF in Command Prompt
If you don’t want to verify every single change
To include subdirectories change
To do all this in a batch file including subdirectories without prompting use below
My contribution for this, converting several files in a folder: for %%z in (*.txt) do (for /f «delims=» %%i in (%%z) do @echo %%i)>%%z.tmp
You could create a simple batch script to do this for you:
Then run and will be instantly converted to DOS line endings.
I cloned my git project using the git bash on windows . All the files then had LF endings. Our repository has CRLF endings as default.
I deleted the project, and then cloned it again using the Windows Command Prompt . The CRLF endings were intact then. In my case, if I had changed the endings for the project, then it would’ve resulted in a huge commit and would’ve caused trouble for my teammates. So, did it this way. Hope this helps somebody.
Based on Endoro’s answer but to keep the blanks, try this:
If you have bash (e.g. git bash), you can use the following script to convert from unix2dos:
similarly, to convert from dos2unix:
Late to the party, but there is still no correct answer using a FOR /F loop.
(But you don’t need a FOR loop at all, the solution from @TampaHaze works too and is much simpler)
The answer from @IR relevant has some drawbacks.
It drops the exclamation marks and can also drop carets.
The trick is to use findstr /n to prefix each line with
: , this avoids skipping of empty lines or lines beginning with ; .
To remove the : the FOR «tokens=1,* delims=:» option can’t be used, because this would remove all leading colons in a line, too.
Therefore the line number is removed by set «line=!line:*:=!» , this requires EnableDelayedExpansion.
But with EnableDelayedExpansion the line set «line=%%L» would drop all exclamation marks and also carets (only when exclams are in the line).
That’s why I disable the delayed expansion before and only enable it for the two lines, where it is required.
The (echo(!line!) looks strange, but has the advantage, that echo( can display any content in !line! and the outer parenthesis avoids accidentials whitespaces at the line end.
Here’s a simple unix2dos.bat file that preserves blank lines and exclamation points:
The output goes to standard out, so redirect unix2dos.bat output to a file if so desired.
It avoids the pitfalls of other previously proposed for /f batch loop solutions by:
1) Working with delayed expansion off, to avoid eating up exclamation marks.
2) Using the for /f tokenizer itself to remove the line number from the findstr /n output lines.
(Using findstr /n is necessary to also get blank lines: They would be dropped if for /f read directly from the input file.)
But, as Jeb pointed out in a comment below, the above solution has one drawback the others don’t: It drops colons at the beginning of lines.
So 2020-04-06 update just for fun, here’s another 1-liner based on findstr.exe, that seems to work fine without the above drawbacks:
The additional tricks are:
3) Use digits 0-9 as delimiters, so that tokens=* skips the initial line number.
4) Use the colon, inserted by findstr /n after the line number, as the token separator after the echo command.
I’ll leave it to Jeb to explain if there are corner cases where echo:something might fail 🙂
All I can say is that this last version successfully restored line endings on my huge batch library, so exceptions, if any, must be quite rare!
Юниксовые утилиты командной строки для Windows // Unix-like command line utilities for Windows
Я фанат командной строки. Точнее, я считаю её весьма удобным инструментом. И использую из Far-а в этих своих Windows. Хе-хе, сколько сразу конфликтных тем – cmdline/gui, Far/TC, Linux/Windows – можно устроить Холивор и Срачъ.
Так вот. Здесь я хочу описать набор утилит командной строки, портированных на Windows, которые считаю удобными и полезными иметь на своём Windows-десктопе. Это именно standalone-бинарники, а не Cygwin, так как я хочу иметь xcopy-style deployment (скопировал куда-нибудь в %PATH% и ололо), без записей в реестр или конфиг-файлы. Все ссылки и версии приведены и работают на настоящий момент, со временем, конечно, версии будут устаревать, а ссылки – протухать.
Почти для всех программ требуется Microsoft Visual C++ 2008 SP1 Redistributable Package, который скорее всего уже есть в системе. Если нет – качать и ставить: x86 и x64 версии. Многие программы взяты из проекта GNUWin32, полный список пакетов смотреть здесь – мало ли, может кому sed понадобится.
- Integrated pack
Всё, что упомянуто ниже, версии на настоящий момент, собрано в один пакет cmdline-unix-4-windows.zip. Распаковываете архив, бинарники из c-windows кладёте в %SystemRoot%, библиотеки из c-windows-system кладёте в %SystemRoot%\system (этот layout работает, по крайней мере, на Windows 7).
На всякий случай рядом лежат рантаймы от VC++ x86 и x64.
Адовый инструмент для скачивания почти чего угодно. Идём на домашнюю страницу виндового порта wget, скачиваем архив с бинарником и архив с зависимостями. wget с версии примерно 1.10 начал поддерживать SSL, поэтому ему теперь нужна SSL-библиотека и еще по мелочи всякого. wget.exe из первого архива кладём в C:\Windows. Библиотеки libeay32.dll, libiconv2.dll, libintl3.dll и libssl32.dll из второго архива кладём в C:\Windows\system. Пыщ.
Адовый инструмент для выполнения запросов к DNS-серверам. То же, что nslookup, только в стопицот раз удобнее. Отдельно его нет, он входит в стандартный комплект DNS-сервера BIND. Идём на домашнюю страницу BIND-a, качаем архив для Windows (на текущий момент последний стабильный релиз – 9.7.3), достаём из архива dig.exe и host.exe, кладём его в C:\Windows. Так как они часть BIND, то требуют кучу его библиотек для своей работы – достаём из архива libbind9.dll, libdns.dll, libisc.dll, libisccfg.dll, liblwres.dll и libxml2.dll и кладём в C:\Windows\system. Также нужен libeay32.dll, если он не скопирован во время установки wget-а. И вот ололо.
Иногда надо потаскать файлы взад-назад с юникс-сервера на виндовый десктоп. Для этого нужен scp из командной строки. Идём на домашнюю страницу PuTTY. Это сам по себе зач0тный инструмент, хотя некоторые ребе считают более кошерным Bitvise Tunnelier, но для моих целей это overkill. Скачиваем по ссылке pscp.exe, переименовываем в scp.exe и кладём в C:\Windows. Вуаля.
Калькулятор командной строки. Берём с домашней страницы виндового порта bc архив с бинарником и архив с зависимостями, кладём bc.exe из первого архива в C:\Windows, кладём readline5.dll из второго архива в C:\Windows\system.
По умолчанию bc.exe работает с целыми числами. Чтобы он считал с, например, 20-ю знаками после запятой надо либо сказать ему scale=20 перед вычислениями, либо запустить с опциями -lq, либо поместить эти опции в переменную окружения BC_ENV_ARGS. Выход из интерактивного режима – Ctrl-D.
Оттуда же берём grep. А так же egrep и fgrep. Бинарники из архива с бинарниками кладём в C:\Windows, библиотеки из архива с зависимостями – в C:\Windows\system.
Иногда возможностей виндового dir не хватает. Отсюда берём портированный ls с виндовыми дополнениями, распаковываем архив и копируем ls.exe в C:\Windows. Почитайте ls.exe ––help – там много интересного.
Иногда надо поработать напрямую с дисками. Прям как в линуксовом dd. Идём на домашнюю страницу, скроллим вниз, берём из архива бинарник dd.exe и кладём в C:\Windows. Сделайте dd.exe ––list 2>&1 | more – увидите всякое.
А вот как потырить MBR с первого диска. Partition0 – весь диск. Запускать, естественно, именем и властью администратора.
- MD5, SHA1 и SFV
Посчитать контрольные суммы скачанного чего-нибудь. md5sum: домашняя страница, бинарник. sha1sum: домашняя страница, бинарник. sfv: источник утерян, но остались сотни ссылок на файлопомойках. Качаем это всё и кладём в C:\Windows.
Заключение
Конечно, здесь не упомянуты более 9000 других «кульных прожек» и «тулзов». Здесь те, которыми пользуюсь лично я.