嘗試 ls | grep pattern | xargs cd 卻報 xargs: cd: No such file or directory?根因在於 cd 是 Shell 內建命令,不在 PATH 中,xargs 無法透過子行程執行並影響父 Shell 的工作目錄。本文說明原理並提供正確替代寫法。
ls | egrep 'nrpe-[0-9]\.[0-9]+$' | xargs ls -ld | xargs cd
# xargs: cd: No such file or directory
xargs 啟動子行程執行命令,cd 在子行程中改變目錄,子行程結束後變更失效,父 Shell 工作目錄不變。cd 為 Shell Builtin,which cd 無輸出,xargs 找不到可執行檔。
# 使用反引號或 $() 將輸出作為 cd 參數,在當前 Shell 執行
cd "`ls | egrep 'nrpe-[0-9]\.[0-9]+$'`"
# 或
cd "$(ls | egrep 'nrpe-[0-9]\.[0-9]+$')"
# 驗證
pwd
# /home/monitor/nagiosclient_db/nrpe-2.12
若管道輸出多行,cd 只能接受單一參數。需先確認唯一性或互動選擇:
# 存入變數檢查行數
dirs=$(ls | egrep 'nrpe-[0-9]\.[0-9]+$')
count=$(echo "$dirs" | wc -l)
if [ "$count" -eq 1 ]; then
cd "$dirs"
else
echo "找到 $count 個目錄,請手動指定:"
echo "$dirs"
fi
# 安裝 fzf
cd "$(ls -d */ | fzf)"
# 彈出互動清單,選擇後自動 cd
| 寫法 | 是否可行 | 說明 |
|---|---|---|
... | xargs cd | ❌ | cd 為 builtin,子行程無效 |
cd $(...) | ✅ | 命令替換,當前 Shell 執行 |
cd "`...`" | ✅ | 舊式命令替換,同樣有效 |
pushd $(...) | ✅ | 保留目錄堆疊,方便返回 |
