Categories
technology

Which command in DOS

I’ve been told that I should add more of the little programming hints and tips that I used to come up with during my reearch days to this site. Well here’s something I was playing around with today that’s useful for many windows developers. Like many programmers I’m often more comfortable at the command line than using some funky GUI where I have to drag (or learn so many command alias key-strokes that I may aswell be at the console anyway).
I was stuck for a UNIX version of the which command. According to man which this command

Which takes a series of program names, and prints out the
full pathname of the program that the shell would call to
execute it. It does this by simulating the shells search-
ing of the $PATH environment variable.

Replicating this functionality using DOS batch ain’t that bad…

@ECHO OFF
rem Sanity check OS version and arguments.
IF "%OS%"=="Windows_NT" (SETLOCAL) ELSE (GOTO Syntax)
IF "%~1"=="" GOTO Syntax
IF NOT "%~2"=="" GOTO Syntax
ECHO.%1 ¦ FIND /V ":" ¦ FIND /V "\" ¦ FIND /V "*" ¦ FIND /V "?" ¦ FIND /V "," ¦ FIND /V ";" ¦ FIND /V "/" ¦ FIND "%1" >NUL
IF ERRORLEVEL 1 GOTO Syntax


SET Found=
rem Get the short name for the current directory
COMMAND /C REM
rem Search CurrentDir, path and pathext for the file
FOR %%A IN (%CD%;%Path%) DO FOR %%B IN (.;%PathExt%) DO IF EXIST "%%~A.\%~1%%~B" CALL :Found "%%~A.\%~1%%~B"
rem Display the result
ECHO.
IF DEFINED Found (ECHO.%Found%) ELSE (ECHO -None-)
rem Done
GOTO End


:Found
IF DEFINED Found GOTO:EOF
rem Store the first match found
SET Found=%~f1
GOTO:EOF
:Syntax
ECHO.
ECHO WHICH, Version 2.00
ECHO UNIX-like WHICH utility for Windows NT 4 / 2000 / XP
ECHO.
ECHO Usage: WHICH program_name
ECHO.
ECHO Specify program_name with or without
ECHO extension and without a drive or path.
ECHO Just like the UNIX command. (no wildcards please)


:End
IF "%OS%"=="Windows_NT" ENDLOCAL

Leave a Reply

Your email address will not be published. Required fields are marked *