Move to folder without using "exec"
Solution 1:
A script indeed runs in a subshell, where the current directory is changed. This environment is killed when the script is ended. Opening an interactive shell (exec zhs
) is needed to interact with the modified environment, which opens yet another subshell than the one your script is running in.
Using a shell function may be most suited for what you want to do.
changedir () {
cd "$1"
echo "Project: $1"
}
Include such function in your ~/.zshrc
file (.bashrc
for bash users). When you exit then reopen the terminal, the command changedir
will be available.
Alternatively, you should source your script rather than executing it. Also that could be implemented rather elegantly by defining an alias:
alias changedir='source <pathname of your script>'
Also an alias definition should be included in ~/.zshrc
(or ~/.bashrc
) to be persistent. Similar to the previous approach, a command changedir
becomes available that autocompletes with Tab.
For a more general use case, where you simply want to switch easily to some directories deep in the tree, see various more options here.