1、执行shell脚本,默认的$(pwd)为执行shell时的目录路径,而不是shell脚本所在路径;
2、在shell脚本中执行cd命令,当脚本执行完后,会退回到执行脚本的目录路径;
[root@localhost b21430]# pwd
/home/b21430
[root@localhost b21430]# ll | grep test.sh
-rw-r--r-- 1 root root 122 Aug 30 10:41 test.sh
[root@localhost b21430]# cat test.sh
#!/bin/bash
set -exuo pipefail
echo " before exec cd $0 $(pwd)"
cd `dirname $0`
echo " after exec cd $0 $(pwd)"
exit 0 --》 /home/b21430/test.sh
[root@localhost b21430]# cd ..
[root@localhost home]# pwd
/home
[root@localhost home]# ll | grep test.sh
-rw-r--r-- 1 root root 148 Aug 30 11:01 test.sh<

本文详细介绍了在Shell脚本中执行cd命令时的一些常见行为和注意事项,包括执行脚本时的当前工作目录、脚本内部cd命令的影响以及在子shell中执行cd的后果。通过示例代码和输出解释了如何正确理解和使用cd来改变目录路径。
最低0.47元/天 解锁文章
2255

被折叠的 条评论
为什么被折叠?



