起因:我在shell中写cd /目录,运行结束后未进入所需目录,但是结果未报错,返回结果为0(正常)。
查询解决:我们常用执行shell脚本的命令是:bash 文件.sh 或者 sh 文件.sh 或者 ./文件.sh,以上命令会重新建立一个子shell,在子shell中执行脚本里面的语句,该子shell继承父shell的环境变量,但子shell新建的、改变的变量不会被带回父shell,除非使用export。因此cd命令会在子shell生效,在我们当前shell下看不到目录变化。所以我们需要另外一种解释命令source filename或者.filename命令。source filename这个命令其实只是简单地读取脚本里面的语句依次在当前shell里面执行,没有建立新的子shell。那么脚本里面所有新建、改变变量的语句都会保存在当前shell里面。同时通常用于重新执行刚修改过的初始化文件,使之立即生效,而不必注销并登录。
root@37fda1a04690:/tmp# cat cd.sh
#!/usr/bin/bash
echo "hello yu" >new.txt
mv /tmp/new.txt /home/
cd /home/
echo $?
root@37fda1a04690:/tmp# ./cd.sh
0
root@37fda1a04690:/tmp# bash cd.sh
0
root@37fda1a04690:/tmp# source cd.sh
0
root@37fda1a04690:/home# cd /tmp/
root@37fda1a04690:/tmp# ls
cd.sh hsperfdata_root
root@37fda1a04690:/tmp# . cd.sh
0
root@37fda1a04690:/home#