4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

指定されたコマンドの場所を表示

Last updated at Posted at 2014-03-04

バッチファイルで書いた which コマンドです。

which コマンドを作る

を参考に、システム環境変数 PATHEXT を参照して拡張子を補完するようにしました。

which.bat
@echo off

set SELF=%~n0
set HELP=使用方法: %SELF% ファイル名 [...]

setlocal enabledelayedexpansion
  :: cmd.exe のビルトインコマンド
  set B=assoc  color  endlocal  if     popd    rename    time   ^
        break  copy   erase     md     prompt  rmdir     title  ^
        call   date   exit      mkdir  pushd   set       type   ^
        cd     del    for       move   rd      setlocal  ver    ^
        chdir  dir    ftype     path   rem     shift     verify ^
        cls    echo   goto      pause  ren     start     vol
  
  if "%*" == "" (
    echo %HELP% >&2
    exit /b 1
  )
  
  :: 検索対象にカレントフォルダを追加
  set PATH=.;%PATH%
  
  set s=
  for %%c in (%*) do (
    :: 拡張子を含んでいるか確認
    if "%%~xc" == "" (
      for %%e in (%PATHEXT%) do (
        for /f %%f in ("%%c%%e") do (
          if exist "%%~$PATH:f" (
            set s=%%~$PATH:f
          )
        )
      )
    ) else (
      if exist "%%~$PATH:c" (
        set s=%%~$PATH:c
      )
    )
    :: ビルトインコマンドか確認
    for %%b in (%B%) do (
      if /i "%%c" == "%%b" (
        set s=%%c is a shell builtin
      )
    )
    
    if "!s!" == "" (
      echo %~n0: no %%c in ^(%PATH%^)
      exit /b 1
    )
    echo !s!
  )
endlocal
goto :EOF

実行すると

C:\>which
使用方法: which ファイル名 [...]

C:\>which cd
cd is a shell builtin

C:\>which ping.exe
C:\WINDOWS\system32\ping.exe

C:\>which ping
C:\WINDOWS\system32\ping.exe

C:\>which kshibamo
which: no kshibamo in (.;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem)
4
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?