Question

My bash script:

#!/bin/bash
cd /tmp

Before running my script:

pwd: /

After running my script:

pwd: /

After runnig my script trough sourcing it:

pwd: /tmp

How I can stay at the path from the script without sourcing it ?

Was it helpful?

Solution

You can't. Changes to the current directory only affect the current process.

OTHER TIPS

Let me elaborate a little bit on this:

When you run the script, bash creates a new process for it, and changes to the current directory only affect that process.

When you source the script, the script is executed directly by the shell you are running, without creating extra processes, so changes to the current directory are visible to your main shell process.

So, as Ignacio pointed out, this can not be done

Ignacio is correct. However, as a heinous hack (totally ill advised and this really should get me at least 10 down votes) you can exec a new shell when you're done

#!/bin/bash
...
cd /
exec bash

If you really need this behavior, you can make your script return the directory, then use it somehow. Something like:

#!/bin/bash
cd /tmp
echo $(pwd)

and then you can

cd $(./script.sh)

Ugly, but does the trick in this simple case.

Here's a silly idea. Use PROMPT_COMMAND. For example:

$ export PROMPT_COMMAND='test -f $CDFILE && cd $(cat $CDFILE) && rm $CDFILE'
$ export CDFILE=/tmp/cd.$$

Then, make the last line of your script be 'pwd > $CDFILE'

You can define a function to run in the current shell to support this. E.g.

md() { mkdir -p "$1" && cd "$1"; }

I have the above in my ~/.bashrc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top