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 cd 無法進入 xargs 管道輸出目錄?原因與解決方案

編輯:關於 Linux

嘗試 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 找不到可執行檔。

正確解法:命令替換 (Command Substitution)


# 使用反引號或 $() 將輸出作為 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 互動式選擇


# 安裝 fzf
cd "$(ls -d */ | fzf)"
# 彈出互動清單,選擇後自動 cd

總結對照表

寫法是否可行說明
... | xargs cd❌cd 為 builtin,子行程無效
cd $(...)✅命令替換,當前 Shell 執行
cd "`...`"✅舊式命令替換,同樣有效
pushd $(...)✅保留目錄堆疊,方便返回

cd xargs 錯誤示意圖

Copyright © Windows教程網 All Rights Reserved