Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call cd in shell script

I have one shell script opening a perl script. This perl script should be opened in a terminal. I am able to open the terminal but I'm unable to call a cd to reach the perl script's location

    $PROJECT_DIR = "$PROJECT_DIR";

    echo "$PROJECT_DIR" > "$PROJECT_DIR/Testing/buildProductPathHello.txt"

osascript -e 'tell app "Terminal"
    do script "pwd"
    do script "cd $PROJECT_DIR" in window 1
    do script "ls" in window 1
    do script "./RunTests.pl" in window 1
end tell'

The variable $PROJECT_DIR contains the path, I am verifying this by writing the path into a file. Ultimately, it's the command cd $PROJECT_DIR is the one that does not work. Does not do cd on the content of the variable.

snapshot of terminal

snapshot 2 PS: this is on a mac with a bash shell

like image 223
i_raqz Avatar asked Jul 10 '26 13:07

i_raqz


2 Answers

Each script runs as its own process, does its thing, and exits. The state of the script, including environment variables and its current directory definition, is discarded when it exits -- so you can't expect a script that does nothing but "cd" to still have effect later.

If instead you did something like this:

do script "cd $PROJECT_DIR; ls; ./runTests.pl"

...then that would do all three commands within a single shell, and the results would be what you expect.

like image 159
Charles Duffy Avatar answered Jul 13 '26 16:07

Charles Duffy


There's no need for cd in this case; just combine your two calls ie do script "$PROJECT_DIR/ls" in window 1

like image 21
ControlAltDel Avatar answered Jul 13 '26 15:07

ControlAltDel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!