Directory stays changed after bash script ends

My bash script:

#!/bin/bash cd /tmp 

Before running my script:

 pwd: / 

After running the script:

 pwd: / 

After running my script trough:

 pwd: /tmp 

How can I stay on the path from a script without searching for it?

+6
bash shell cd
source share
6 answers

You can not. Changes in the current directory affect only the current process.

+11
source share

Let me elaborate on this:

When the script starts, bash creates a new process for it, and changes in the current directory affect only this process.

When you submit a script, the script is executed directly by the shell that you run without creating additional processes, so changes to the current directory are displayed in the main shell process.

So, as Ignacio pointed out, this is impossible to do.

+5
source share

Ignacio is correct. However, as a disgusting hack (absolutely not recommended, and this should really give me at least 10 votes), you can execute a new shell when you're done

  #! / bin / bash
 ...
 cd /
 exec bash
+2
source share

If you really need this behavior, you can return your script directory and 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.

+1
source share

Here is a stupid 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'

+1
source share

You can define a function that will be launched in the current shell to support it. For example.

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

I have higher in my ~ / .bashrc

0
source share

All Articles