i_raqz
i_raqz

Reputation: 2959

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

Upvotes: 2

Views: 2220

Answers (3)

paulmelnikow
paulmelnikow

Reputation: 17218

Environment variables are specific to each process, too.

The way you're invoking osascript, with a single-quoted string, tells the original instance of bash not to substitute for variable names. It actually sends "cd $PROJECT_DIR" to osascript, which sends cd $PROJECT_DIR to Terminal.

But $PROJECT_DIR is not set in the receiving bash process – the one running inside your Terminal window. You can verify that by adding a line like do script "set" in window 1 or do script "echo $PROJECT_DIR" in window 1.

If you enclose the part of the script with the variable name in double quotes, the original bash process will substitute the value of $PROJECT_DIR instead:

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'

(syntax suggested by CharlesDuffy)

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295766

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.

Upvotes: 7

ControlAltDel
ControlAltDel

Reputation: 35106

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

Upvotes: 3

Related Questions