Possible to change directory and have change persist when script finishes?
<p>In trying to answer <a href="http://stackoverflow.com/q/39776616/3642398">a question for another user</a>, I came across something that piqued my curiosity:</p>

<pre><code>import os
os.chdir('..')
</code></pre>

<p>Will change the working directory as far as Python is concerned, so if I am in <code>/home/username/</code>, and I run <code>os.chdir('..')</code>, any subsequent code will work as though I am in <code>/home/</code>. For example, if I then do:</p>

<pre><code>import glob
files = glob.glob('*.py')
</code></pre>

<p><code>files</code> will be a list of <code>.py</code> files in <code>/home/</code> rather than in <code>/home/username/</code>. However, as soon as the script exits, I will be back in <code>/home/username/</code>, or whichever directory I ran the script from originally.</p>

<p>I have found the same thing happens with shell scripts. If I have the following script:</p>

<pre><code>#!/bin/bash

cd /tmp
touch foo.txt
</code></pre>

<p>Running the script from <code>/home/username/</code> will create a file <code>foo.txt</code> in <code>/tmp/</code>, but when the script finishes, I will still be in <code>/home/username/</code> not <code>/tmp/</code>. </p>

<p>I am curious if there is some fundamental reason why the working directory is not changed "permanently" in these cases, and if there <em>is</em> a way to change it permanently, e.g., to run a script with <code>~$ python myscript.py</code>, and have the terminal that script was run from end up in a different directory when the script finishes executing. </p>

<p>There is no way to do that because calling Python or bash will run everything within their own context (that ends when the script ends).</p>

<p>You could achieve those results by using <code>source</code>, since that will actually execute your (shell) script in the current shell. i.e., call your example script with <code>source foomaker.bash</code> instead of <code>bash foomaker.bash</code></p>

python