When I change working directory in a script and execute it, the working directory only changes to specified path while in the script. Here is my script:#!/bin/bash (this was to make sure if it actually changed directory)
cd /media/hard/drive/partitionX/
pwd
When I execute it, it returns the specified path, but my working directory in terminal doesn't change. How do I change the working directory in my terminal through a script?
12 Answers
This is normal. The "current" or "working" directory is a per-process parameter, and a process can only change its own working directory. Standalone scripts are executed as a separate shell process and cannot affect the parent shell (in fact, the parent might not always be a shell).
You will need to use features internal to your shell, such as:
shell functions:
mycd() { cd /media/hard/drive/partitionX/; pwd; }shell aliases:
alias mycd='cd /media/hard/drive/partitionX; pwd'"source" a script instead of executing it:
. mycd.sh
If your main goal is to create shortcuts to certain directories, you can also use:
symlinks in a more convenient location:
ln -s /media/hard/drive/partitionX ~/partX cd ~/partXvariables ($mydir):
mydir=/media/hard/drive cd $mydirthe $CDPATH feature:
CDPATH=".:/media/hard/drive" cd partitionX
Actually, I just found, after many searches, that if you need to change the directory, and still keep the same shell, so you will get all the answers in your currect script, you can use:
(cd your_dir; do_some_command_there)For example, what I needed to use, was:
((cd your_dir; git remote -v | wc -l)Works like a charm!