2

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..

kamziro
  • 141

2 Answers2

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.

1

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".

Kusalananda
  • 333,661