2

This question already has an answer here:

I was wondering if it's possible to change directory of a shell from a bash script, but keep the directory change persistent to more than just the subshell.

I'm aware that when you run cd inside a bash script the directory will only change inside the subshell, and when you get back out you'll return to whatever directory you were in.

However, I want to make a command to bring me to certain directories. I could use an alias, but there are a lot of subdirectories that I would have to make an alias for..

marked as duplicate by Jeff Schaller, JigglyNaga, schily, Jesse_b, RalfFriedl Nov 15 '18 at 18:14

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Only if you source the script, rather than execute it. – jordanm Nov 15 '18 at 4:18
  • Unless your source such a script, you can't make the changes reflect in the parent shell – Inian Nov 15 '18 at 4:18
  • 1
    So make a function. – muru Nov 15 '18 at 4:19
  • This surely must be a dup? – roaima Nov 15 '18 at 8:43
1

No, scripts are executed in a separate shell, which doesn't affect its ancestors. But you could use a function, which takes arguments, and so is more flexible than alias. Another option is sourcing files with source or its equivalent ., but that doesn't accept arguments. Still, it affects the current shell. You might combine the two and put functions in a file that you'd source and then use the functions in the current process.

0

You probably are looking for something like the CDPATH shell variable.

The CDPATH variable acts like PATH but for the cd command.

Setting with something like

CDPATH=".:~:~/projects:~/music"

would allow you to say

cd ricky_martin

anywhere, and it would go through the :-separated directory paths in the $CDPATH value in order until it found a subdirectory called ricky_martin somewhere (possibly ~/music/ricky_martin) and then cd there.

Likewise

cd world_domination

may take you to ~/projects/world_domination if there is such a subdirectory. If world_domination also existed in the current directory, this directory would be selected first as it occurs earlier in $CDPATH (the dot in the first position).

It would also be allowed to do

cd proj1/tests

from anywhere to get to ~/projects/proj1/tests if such a directory existed (with the above $CDPATH value, unless proj/tests did not exist in the current directory or in your home directory).

Note that the CDPATH shell variable should not be exported as that may seriously confuse some scripts.

The CDPATH variable is documented in the bash manual (man bash):

CDPATH

The search path for the cd command. This is a colon-separated list of directories in which the shell looks for destination directories specified by the cd command. A sample value is ".:~:/usr".

Not the answer you're looking for? Browse other questions tagged or ask your own question.