Recently I was learning shell scripts and wrote a simple demo. What I want to achieve is to cd a folder and then create files, but when I execute the shell script, I find that the cd command does not take effect. My folders and files are not created
# !/bin/bash
read -p "请输入文件夹的名字:" dirName
if [ -e $dirName ];then
echo "$dirName 是存在的即将进入文件夹"
cd $dirNamem
echo "即将创建文件名为test"
touch test.c
else
echo "该文件夹不存在,即将创建文件夹"
mkdir $dirName
echo "即将进入$dirName 文件夹中"
cd $dirName
I checked the information and found that this is because when the shell executes the script, it creates a subshell and executes the commands in the script one by one in the subshell; while the subshell inherits the environment variables from the parent shell, but executes Will not change the environment variables of the parent shell.
I used two methods to make my cd take effect.
- Use the source command
When executing a shell script, do not use ./XXX.sh. Instead, use the source xxx.sh method, this will create a file, but directly return to the ~ directory (does not solve the cd not) - Adding
the command exec /bin/bash after cd means that the bash script runs on its current environment or its child environment, but not on its parent environment