script to change shell's pwd

Hi there,

i was presented with a challenge that is beyond my current shell knowledge: how can you have a script that executed interactive will change your current working directory?

Example (under MacOS):

  1. start Terminal and my current working directory is my home folder
  2. execute a script that, when completed, will change my shell's working directory to something else....

Is this doable?

Yes. IF you source a script it runs in the conext of the current process rather than as a child

two ways

# bash source command
source myscript.sh
# standard for other shells
. myscript.sh
1 Like

jim,

your suggestion does work but it's not quite i had in mind....
I'll provide additional details: let's assume that i want to change the behaviour of built-in ls command, where by typing:
ls folder_name
instead of listing the content of that folder, it will list the content AND change directory to that folder.

there must be a way to do it, isn't it? :slight_smile:

If you take the question literally, then no. The shell has to change its own directory, nothing from the outside can force it to change. Any external program will have its own, separate, current directory and changing it won't change the shell's.

You can tell the shell to execute a script internally, though, which is how jim's solution works. The effect of a sourced script is the same as if you'd typed it into your shell.

---------- Post updated at 12:19 PM ---------- Previous update was at 12:16 PM ----------

"built-in" has a specific meaning in the context of shell languages, and ls is not a built-in. It's an external program. Quite a few things you use in the shell probably aren't built-ins.

If you have bash or ksh, you could do it with a function I suppose:

function lcd
{
        ls "$1" && [ -d "$1" ] && cd "$1"
}

lcd folder

The [ -d ] part is so it doesn't bother cd-ing into non-folders.

1 Like