0

I want to write a shell script where i change directory and then execute a command inside that directory. How come i cannot change directory? It does not work whenever i do:

#!/bin/bash

cd /something/something

What am i doing wrong? /Daniel

Hermansson
  • 27
  • 4
  • 5
    You are perfectly changing the directory. However, just within the scope of the script, so when it finishes you are back into the reality of the session you were working on. You may want to use `source file` instead, so that the command gets executed in the current shell. – fedorqui Jul 29 '15 at 13:17

1 Answers1

0

When you run a shell script a new shell is created. So thus when the shell script exits the shell the script is running in is destroyed and you thus return to your current shell. Which is probably a good thing since in some shell scripts you are making a ton of variables and stuff of that nature that you don't want lurking around after the script is done executing.

Due to the shell script shell being blown away and you being returned to you original shell the change of directory will not be reflected in the interactive shell you are using.

There is a command called source though which executes the shell script in the current shell and thus would cd in your current shell and make any other changes done in the script until you exit your current shell.

If however in the script you are using there is no cd at all happening when the new shell is made, this can be due to the file permissions on a directory. If a directory has a chmod -x no execute permission set, you can not cd into that directory as you need execute permissions on a directory to enter that directory.

jgr208
  • 2,896
  • 9
  • 36
  • 64
  • Thanks for the answers. I solved the problem by inserting a function with the path inside .bashrc and calling it from the terminal. startf () { cd /something/something } – Hermansson Jul 30 '15 at 14:32
  • huh? so everytime you start a new shell its cds to the directory? @Hermansson – jgr208 Jul 30 '15 at 17:42