0

In my VM, my projects are at /var/www/vhosts/projectname/httpdocs/.
When I boot the machine, I start at /home/vagrant/.

I created a script that instantly takes me to the project I want. The problem is, the script uses exec and creates a new session every time I use it.

This is my code:

#!/usr/bin/env zsh

if [ -z "$1" ]; then echo "No project specified" exit 1 fi

cd /var/www/vhosts/"$1"/httpdocs/ || exit

echo "---------------------" echo "Project: $1" echo " https://$1.vm/" echo " https://$1.vm/typo3" echo "---------------------"

exec zsh

Is there another way to set my current path without creating a new session?
Thanks

tiimo
  • 3
  • 1

1 Answers1

4

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.

vanadium
  • 97,564