you're running a script with a subshell.
the problem with running cd
inside a script is that it creates a subshell starting from that directory. when the script ends, so does your subshell, and you're back where you started when you ran the script. so it goes like this:
- start script
- subshell is created
- create directory
- change to directory
- end script
- end subshell
- back to starting point
you can prove that cd
works in the script and that you're inside that directory while executing your script by leaving a mark.
t=$(date +%F-%H%M%S)
mkdir $t
cd $t
echo "I'm here" > inside.txt
now when the script ends, you'll be back where you started the script. but if you cd
to the directory, and run ls
, then you'll see the file you made.
as @Dawid Ferenczy points out, you can actually source
this script into your current shell instead of running a subshell, such as:
source test.sh