- Is there an equivalent of ‘which’ on the Windows command line?
- 26 Answers 26
- Finding executables using only part of the name
- Finding custom executables
- Команды type, which, whereis, whatis и locate
- Команда type
- Команда which
- Команда whereis
- Команда whatis
- Команда locate
- Сответствие консольных команд Windows и Linux.
Is there an equivalent of ‘which’ on the Windows command line?
As I sometimes have path problems, where one of my own cmd scripts is hidden (shadowed) by another program (earlier on the path), I would like to be able to find the full path to a program on the Windows command line, given just its name.
Is there an equivalent to the UNIX command ‘which’?
On UNIX, which command prints the full path of the given command to easily find and repair these shadowing problems.
26 Answers 26
Windows Server 2003 and later (i.e. anything after Windows XP 32 bit) provide the where.exe program which does some of what which does, though it matches all types of files, not just executable commands. (It does not match built-in shell commands like cd .) It will even accept wildcards, so where nt* finds all files in your %PATH% and current directory whose names start with nt .
Try where /? for help.
Note that Windows PowerShell defines where as an alias for the Where-Object cmdlet, so if you want where.exe , you need to type the full name instead of omitting the .exe extension.
While later versions of Windows have a where command, you can also do this with Windows XP by using the environment variable modifiers, as follows:
You don’t need any extra tools and it’s not limited to PATH since you can substitute any environment variable (in the path format, of course) that you wish to use.
And, if you want one that can handle all the extensions in PATHEXT (as Windows itself does), this one does the trick:
It actually returns all possibilities but you can tweak it quite easily for specific search rules.
$PATH:%i To add it to an alias.bat script that you load everytime you run cmd.exe (put the above script in a new directory called C:\usr\aliases): DOSKEY which=C:\usr\aliases\which.bat $* Then you can make a script to launch cmd.exe with the alias.bat file: cmd.exe /K E:\usr\aliases\alias.bat – Brad T. Apr 25 ’14 at 20:42
Under PowerShell, Get-Command will find executables anywhere in $Env:PATH .
And since powershell let’s you define aliases, which can be defined like so.
PowerShell commands are not just executable files ( .exe , .ps1 , etc). They can also be cmdlets, functions, aliases, custom executable suffixes set in $Env:PATHEXT , etc. Get-Command is able to find and list all of these commands (quite akin to Bash’s type -a foo ). This alone makes it better than where.exe , which.exe , etc which are typically limited to finding just executables.
Finding executables using only part of the name
Finding custom executables
Unlike UNIX, where executables are files with the executable ( +x ) bit set, executables on windows are files present in one of the directories specified in the $PATH env. variable whose filename suffixes are named in the $PATHEXT env. variable (defaults to .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL ).
As Get-Command also honours this env. variable, it can be extended to list custom executables. e.g.
See Get-Command for more options and examples.
In Windows PowerShell:
If you have PowerShell installed (which I recommend), you can use the following command as a rough equivalent (substitute programName for your executable’s name):
The GnuWin32 tools have which , along with a whole slew of other Unix tools.
In Windows CMD which calls where :
Cygwin is a solution. If you don’t mind using a third-party solution, then Cygwin is the way to go.
Cygwin gives you the comfort of *nix in the Windows environment (and you can use it in your Windows command shell, or use a *nix shell of your choice). It gives you a whole host of *nix commands (like which ) for Windows, and you can just include that directory in your PATH .
In PowerShell, it is gcm , which gives formatted information about other commands. If you want to retrieve only path to executable, use .Source .
For instance: gcm git or (gcm git).Source
- Available for Windows XP.
- Available since PowerShell 1.0.
- gcm is an alias of Get-Command cmdlet.
- Without any parameters, it lists down all the available commands offered by the host shell.
- You can create a custom alias with Set-Alias which gcm and use it like: (which git).Source .
- Official docs: https://technet.microsoft.com/en-us/library/ee176842.aspx
I have a function in my PowerShell profile named ‘which’
Here’s what the output looks like:
gold on windows platforms, puts all the nice unix utilities on a standard windows DOS. Been using it for years.
It has a ‘which’ included. Note that it’s case sensitive though.
NB: to install it explode the zip somewhere and add . \UnxUtils\usr\local\wbin\ to your system path env variable.
If you can find a free Pascal compiler, you can compile this. At least it works and shows the algorithm necessary.
Not in stock Windows but it is provided by Services for Unix and there are several simple batch scripts floating around that accomplish the same thing such this this one.
The best version of this I’ve found on Windows is Joseph Newcomer’s «whereis» utility, which is available (with source) from his site.
The article about the development of «whereis» is worth reading.
None of the Win32 ports of Unix which that I could find on the Internet are satistactory, because they all have one or more of these shortcomings:
- No support for Windows PATHEXT variable. (Which defines the list of extensions implicitely added to each command before scanning the path, and in which order.) (I use a lot of tcl scripts, and no publicly available which tool could find them.)
- No support for cmd.exe code pages, which makes them display paths with non-ascii characters incorrectly. (I’m very sensitive to that, with the ç in my first name :-))
- No support for the distinct search rules in cmd.exe and the PowerShell command line. (No publicly available tool will find .ps1 scripts in a PowerShell window, but not in a cmd window!)
So I eventually wrote my own which, that suports all the above correctly.
Команды type, which, whereis, whatis и locate
Команда type
Команда type позволяет выяснить, содержится ли некоторая команда в системе, и определить тип данной команды. Команда также сообщает, является ли название команды действительным и где именно в системе находится эта команда:
Команда which
Команда which выводит полный путь до команды, если она находится в пути поиска $PATH . Команда which показывает первую найденную команду в переменной $PATH . Если надо проверить существование нескольких совпадений, используется опция -a :
Команда whereis
Команда whereis позволяет найти не только исполняемые файлы, но и файлы документации и конфигурации. Выполняет поиск в ограниченном количестве каталогов, например в каталогах стандартных двоичных файлов, каталогах библиотек и в каталогах man .
Команда whatis
Команда whatis показывает краткую информацию о команде из ее man-страницы.
Команда locate
Команда locate выполняет поиск по базе данных имен файлов, хранящейся в Linux. Для получения актуальных результатов, необходимо регулярно обновлять базу данных со списком имен файлов. Чаще всего ОС настроена таким образом, что обновление будет выполняться автоматически. Если обновление по умолчанию отключено, можно обновить базу данных вручную:
- -q — позволяет скрыть сообщения об ошибках (например, нет доступа к файлу)
- -n — позволяет ограничить количество возвращаемых результатов
- -c — позволяет узнать количество файлов, соответствующих заданному критерию поиска
- -i — позволяет провести поиск файлов без учета регистра
Сответствие консольных команд Windows и Linux.
При переходе с Windows на Linux и наоборот, для тех, кто знаком с командной строкой, может пригодиться небольшая справка по соответствию консольных команд этих операционных систем. Естественно, полного соответствия, за редким исключением, не бывает, и в приведенной таблице собраны команды, идентичные по результатам выполнения или функционально близкие.
Соответствие команд CMD Windows командам Linux
Описание | Команда CMD Windows | Команда Linux |
Вызов справочной системы | HELP | apropos, man, whatis |
Вызов командного интерпретатора (оболочки) | CMD | bash, csh, sh |
Очистка экрана | CLS | clear, reset |
Вывод сообщения на экран | ECHO | echo |
Пауза в работе | PAUSE | sleep |
Настройка параметров терминала | MODE | stty |
Установка значений переменных окружения (указание путей к каталогам) | PATH, SET, SETx | env, set |
Изменение системной даты | DATE | date |
Изменение системного времени | TIME | date |
Выход из командной строки | EXIT | exit |
Работа с файлами и каталогами | ||
Отображение списка файлов и каталогов | DIR | dir, ls |
Создание каталога | MKDIR | mkdir |
Удаление каталога | RMDIR | rmdir |
Удаление файла | DEL, ERASE | rm |
Переход в другой каталог | CD | cd |
Копирование файлов или каталогов | COPY, XCOPY | cp |
Переименование файла | REN, RENAME | mv |
Перемещение файлов | MOVE | mv |
Поиск файла | WHERE | find, locate |
Вывод на экран содержимого файла | TYPE, MORE | cat, less, more |
Сравнение содержимого двух файлов | COMP, FC | cmp, diff, diff3, sdiff |
Сортировка строк в текстовом файле | SORT | sort |
Изменение атрибутов файла | ATTRIB | chmod |
Создание символьной ссылки на файл или каталог | MKLINK | ln |
Резервное копирование данных | ROBOCOPY | cpio, tar |
Вызов текстового редактора | EDIT (нет в Windows Vista и старше) | vi |
Работа с томами и разделами | ||
Создание разделов | FDISK | fdisk |
Управление разделами | DISKPART | parted, partx |
Форматирование диска, создание файловой системы | DISKPART, FORMAT | mformat, mkfs |
Проверка файловой системы | CHKDSK | fsck |
Управление системой. | ||
Отобразить список процессов | TASKLIST, QUERY PROCESS | ps |
Уничтожить процесс | TASKKILL | kill, killall |
Перезагрузить компьютер | SHUTDOWN | shutdown, reboot |
Выключить компьютер | SHUTDOWN | shutdown, halt |
Выполнить команду от имени другого пользователя | RUNAS | sudo |
Отобразить имя компьютера | HOSTNAME | hostname |
Пользователи и группы. | ||
Создать нового пользователя | NET USER | useradd |
Изменить параметры пользователя | NET USER | usermod |
Изменить пароль пользователя | NET USER | passwd |
Удалить пользователя | NET USER | userdel |
Создать новую группу пользователей | NET GROUP | groupadd |
Изменить параметры группы | NET GROUP | groupmod |
Удалить группу | NET GROUP | groupdel |
Отобразить список активных пользователей | QUERY USER | users |
Работа с сетью. | ||
Работа с таблицей соответствия IP и MAC адресов ARP | arp | arp |
Конфигурация протокола IP | IPCONFIG, NETSH | ifconfig, ip |
Работа с таблицей маршрутизации | ROUTE | route |
Опрос узла по протоколу ICMP | PING | ping |
Клиент Telnet | TELNET | telnet |
Работа с DNS-сервером в интерактивном режиме | NSLOOKUP | dig, nslookup |
Трассировка маршрута к удаленному узлу | TRACERT | traceroute |
Отобразить статистику сетевых соединений | NETSTAT | netstat |
Строчные и заглавные буквы для команд командной строки Windows воспринимаются одинаково, ECHO и echo — будет интерпретировано как одна и та же команда. При работе в командной строке Linux соблюдение регистра символов обязательно.
Если вы желаете помочь развитию проекта, можете воспользоваться кнопкой «Поделиться» для своей социальной сети