撰寫 Shell 腳本時常遇到:ls | grep pattern | xargs cd 報錯 xargs: cd: No such file or directory。本文解析根因並提供解決方案。
[root@test1 nagiosclient_db]# ls | egrep 'nrpe-[0-9].[0-9]+.$' | xargs ls -ld | xargs cd xargs: cd: No such file or directory
[root@test1 nagiosclient_db]# cd "`ls | egrep 'nrpe-[0-9].[0-9]+.$' `" [root@test1 nrpe-2.12]# pwd /home/monitor/nagiosclient_db/nrpe-2.12
[root@test1 nrpe-2.12]# which cd /usr/bin/which: no cd in (/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin) [root@test1 nrpe-2.12]# which xargs /usr/bin/xargs
cd 無絕對路徑證明為內建命令;xargs 為外部執行檔。
cd "$(command)" 或反引號find -exec 或 while read 迴圈