- 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/WSL Interop with AF_UNIX
- How To Code
- Requirements & Limitations:
- Binding Sample 1: No Windows Permissions
- Binding Sample 2: Linux Permissions, No Windows Permissions
- Binding Sample 3: No Linux Permissions, Windows Permissions
- Sample Code
- Windows Server code
- Linux code
- Команда which в Linux [с примерами]
- Linux, Примеры команды which
- Использование команды which с несколькими исполняемыми файлами
- Показать все пути с командой which
- Статус вывода команды which
- Windows command to convert Unix line endings?
- 17 Answers 17
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/WSL Interop with AF_UNIX
February 7th, 2018
Starting in Windows Insider build 17093, a WSL application can communicate with a Windows application over Unix sockets. Back in December, we blogged about bringing AF_UNIX to Windows. Now, we’re building on that functionality. Consider a requirement where you want to run some kind of service as a Windows application. Additionally, you would like to make this service available to both Windows and WSL applications. Now, that’s possible with Unix sockets.
How To Code
Let’s look at how the code for such applications would be written.
The code for this application is at the bottom of this article.
One thing worth noting is the path of the socket. For Windows application, the path is in Win32 format and for WSL applications, the format is as in Linux file system.
Requirements & Limitations:
- A WSL Unix socket can only communicate with a Win32 Unix socket OR with a WSL Unix socket, but not both. For instance, a WSL Unix socket server can only accept connections from either WSL Unix socket(s) OR Win32 Unix socket(s). So, how is it determined which one is it? It’s based on the path the socket is bound to or connecting to, as specified in the `bind` or `connect` syscall. If the Unix socket path is a DrvFS path (i.e your system volumes mounted within WSL, ex: /mnt/c, /mnt/d etc.) then it can only communicate to a Windows Unix socket. If the path is a LxFS path (i.e Linux mounted volume within WSL, ex: /home, /var, /usr etc.) then it can only communicate with WSL Unix sockets.
- For a WSL Unix socket to establish connection with Windows Unix sockets, the first operation after the socket is created should be either a bind or connect. Any other operation on the socket will render it an exclusive WSL Unix socket that can only communicate with other WSL Unix sockets.
- As Windows Unix socket implementation does not currently support passing ancillary data such as `SCM_RIGHTS` etc., the ancillary data will also not be supported for Win32 WSL interop over Unix sockets.
It is important to note that we enforce both Unix and Windows permissions for Unix interop between WSL/Windows–this is illustrated in the samples below.
NOTE: Turn on DrvFS metadata for these examples.
Binding Sample 1: No Windows Permissions
In this sample, we’ll bind a WSL Unix socket process to a path which it does not have access to. The binding will fail because I don’t have write permissions in Windows.
But grant write access to the path in Windows and it will bind successfully…
Binding Sample 2: Linux Permissions, No Windows Permissions
In this sample, a WSL Unix socket process connects to a Windows Unix socket path which it has access to from WSL, but not from Windows (I removed write permissions from user on this folder in Windows)
But if I run an elevated ubuntu (so that we do have write access on the file), I can connect as expected.
Binding Sample 3: No Linux Permissions, Windows Permissions
In this sample, a WSL Unix socket process connects to a Windows Unix socket path which it has access to from Windows, but not from WSL. You’ll see that I revoke access in WSL, which causes my client to fail to connect. Then, I’ll grant write access in WSL and the client will succeed.
Sample Code
Windows Server code
Linux code
Cheers, from Sunil Muthuswamy and Craig (@CraigWilhite)
Команда which в Linux [с примерами]
Другими словами, если вам интересно, где именно находится определенная программа, просто используйте which. Команда Linux имеет простой синтаксис:
Давайте посмотрим, как использовать эту простую, но полезную команду.
Linux, Примеры команды which
Допустим, вы хотите знать, где находится исполняемый файл Java, используйте команду:
Вывод может быть таким:
$ which java
/usr/bin/java
Обратите внимание, что работает только с исполняемыми файлами. Таким образом, вы должны использовать which только с аргументом. Например, вы устанавливаете Java с помощью пакета JDK, но не запускаете команду с именем «jdk», вы запускаете «java». Таким образом, вы используете команду which на Java, а не JDK.
Если команда which не находит исполняемый файл в текущем пути, она ничего не возвращает.
Использование команды which с несколькими исполняемыми файлами
Вы можете предоставить более одного аргумента для команды which:
Вывод для нас был такой:
$ which man java python nada
/usr/bin/man
/usr/bin/java
/usr/bin/python
Вы заметили что-то здесь? Мы дали ему четыре аргумента, но результат отображается только для трех из них. Это потому, что «nada» не исполняемый файл. Там нет вывода для which.
Показать все пути с командой which
Команда which в Linux имеет только одну опцию -a. По умолчанию эта команда печатает только один путь для своих аргументов.
Если программа имеет исполняемый файл в двух местах, например, в /usr/bin/program и в /usr/local/bin/program, вы можете отобразить оба пути с помощью опции -a.
Статус вывода команды which
Если вы используете команду which в скрипте bash, вам может потребоваться узнать ее состояние завершения.
Команда which имеет следующий статус выхода:
- 0 – все аргументы найдены и выполняются
- 1 – один или несколько аргументов не существуют или не выполняются
- 2 – если указан неверный параметр
Это все, что вам нужно знать о команде which в Linux. Если у вас есть вопросы или предложения, дайте нам знать в комментариях ниже.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
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!