Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to change directory and have change persist when script finishes?

Tags:

python

In trying to answer a question for another user, I came across something that piqued my curiosity:

import os
os.chdir('..')

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

import glob
files = glob.glob('*.py')

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

I have found the same thing happens with shell scripts. If I have the following script:

#!/bin/bash

cd /tmp
touch foo.txt

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

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

like image 495
elethan Avatar asked Sep 29 '16 18:09

elethan


1 Answers

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

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

like image 177
campos.ddc Avatar answered Oct 22 '22 07:10

campos.ddc