【Linux笔记】cd无法进入xargs管道输出的目录

本文详细介绍了在使用Shell脚本时,如何解决cd命令无法进入通过xargs管道输出目录的问题。通过修改命令结构,确保能够正确进入指定目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在写shell脚本的时候,想用cd进入xargs管道输出的目录,但是提示报错。详情如下:

【环境描述】

目录结构:

[root@test1 nagiosclient_db]# ls -ltr
total 2488
-rw-r--r--.        1     root   root    405725   Mar  3 14:12   nrpe-2.12.tar.gz
-rw-r--r--.        1     root   root    2095419 Mar  3 14:12   nagios-plugins-1.4.15.tar.gz
drwxrwxrwx.   16   501  root    4096        Mar  3 14:36   nagios-plugins-1.4.15
drwxrwxr-x.     7     500  500    4096        Mar  3 14:37   nrpe-2.12

获取需要的目录:

[root@test1 nagiosclient_db]# ls | egrep 'nrpe-[0-9].[0-9]+.$'
nrpe-2.12

使用管道进入指定的目录:

[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

进入了指定的目录。


【为什么cd命令不能进入xargs管道输出的目录】

xargs牵涉写管道,而cd是内部命令。具体的牵涉shell的工作原理。

查看cd命令的绝对路径:

[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)

查看xargs的绝对命令:

[root@test1 nrpe-2.12]# which xargs
/usr/bin/xargs

详情如上,因非系统工程师,故此处不对shell的原理做深入研究。


【参考链接】

http://bbs.chinaunix.net/thread-750335-2-1.html

http://blog.youkuaiyun.com/jason_asia/article/details/28407189

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值