8

I'm trying to run a simple script- clone a git repository into a certain directory, then cd to this directory in order to execute an installation script.

This script is in a Makefile.

But the cd seems not to be working. It doesn't find my installation script.

I added a pwd after the cd in the script, and it shows me the directory from where I'm executing the script, not the directory where I cd into.

What's the problem?

git clone http://somerepo ~/some_dir
cd ~/some_dir/
pwd
python myscript.py install

=>

pwd: /hereIsPathToDirectoryFromWhichIRunTheScript

python: can't open file 'setup.py': [Errno 2] No such file or directory

It also doesn't work with ./setup.py.

If I enter the absolute path ~/some_dir/setup.py the script fails later because it's trying to access resources in the same folder.

  • Can you try something like: "alias mycd='cd some_dir';mycd" – alpert Aug 18 '14 at 13:49
  • That doesn't work: /bin/sh: mycd: command not found – Ixx Aug 18 '14 at 13:51
  • I found the solution: stackoverflow.com/questions/1789594/… had to add a ; after the cd and then execute the script in the same line. – Ixx Aug 18 '14 at 13:54
24

You're using a makefile. Makefiles aren't scripts, each line is executed in a new shell. Meaning when you change the environment in line (such as cd), that change is not propagated to the next line.

The solution is that when you want to preserve the environment between commands, you run all the commands in the same line. All the commands will then be executed in the same shell, and the environment is preserved.

For example:

target:
    git clone http://somerepo ~/some_dir
    cd ~/some_dir/ && python myscript.py install
0

A script is run in a subshell, which means it has its own $PWD. Once it exits you get the "old" $PWD. If you want to keep the $PWD you need to source (aka. .) the script instead of running it. This won't work in a Makefile, however, because each command is run in a separate subshell:

$ pwd
/home/user
$ cat test.sh
cd /
$ cat Makefile
test:
    . ./test.sh && pwd
    pwd
$ make test
. ./test.sh && pwd
/
pwd
/home/user

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.