Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux which 指令完整用法:尋找可執行檔路徑、繞過 alias、判斷內建指令

編輯:關於 Linux

which 只搜尋 $PATH 中的可執行檔,不包含 Shell 內建指令 (如 cd)、別名、函數。本文詳細說明參數、實戰範例、常見誤區與替代工具 (type、command -v)。

指令格式

which [選項] 指令名稱...

常用參數

參數說明
-a列出 $PATH 中所有同名可執行檔 (不只第一個)
-p同 -a,但包含路徑 (部分實作)
--skip-alias忽略 alias (GNU which 專有)
--skip-functions忽略 Shell 函數
--read-alias從 stdin 讀取 alias 定義 (搭配 alias | which --read-alias)

實戰範例

# 1. 尋找單一指令
$ which ls
/bin/ls

# 2. 列出所有同名指令 (發現被覆蓋的版本)
$ which -a python
/usr/bin/python
/usr/local/bin/python

# 3. 判斷指令來源類型 (which 做不到)
$ type -a ls
ls is aliased to `ls --color=auto'
ls is /bin/ls

$ type cd
cd is a shell builtin

# 4. 腳本中安全取得路徑 (POSIX)
command -v grep   # 標準、不受 alias 影響

常見誤區

以為 which 能找到 cd、echo 等內建指令
內建指令不在 $PATH 中,which 回傳空或錯誤。請用 type 或 command -v。
which 回傳的路徑就是實際執行的
若有同名 alias/function,實際執行順序:alias → function → builtin → $PATH。which 只看最後一層。
不同使用者 which 結果不同
$PATH 不同 (如 root vs 一般用戶),which 結果隨之變化。

進階:type vs command -v vs which

工具標準支援內建支援 alias支援函數輸出類型
which非 POSIX否否 (預設)否路徑
typeBash 內建是是是描述+路徑
command -vPOSIX是否 (忽略)否路徑
command -VPOSIX是是是描述

腳本最佳實務

#!/bin/sh
# 可攜性最高:command -v
GREP=$(command -v grep) || { echo "grep not found"; exit 1; }
$GREP "pattern" file

善用 type 除錯指令來源,command -v 撰寫可攜腳本,which -a 排查版本衝突。

Copyright © Windows教程網 All Rights Reserved