Score:0

Move to folder without using "exec"

in flag

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

muru avatar
us flag
Why do you need a script? Why not write a function and put everything except the `exec zsh` in it?
bac0n avatar
cn flag
..... and change all exit to return ...
Score:4
cn flag

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 avatar
cn flag
@steeldriver right you are, and wrong I was. Probably a shell function is most suited for this job, which I now included in the answer.

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.