4

I am stuck in changing the directory in a shell script in linux.

#!/bin/sh
cd /driver

The above does not change the directory. Shell is running in its own context so it can not provide linux terminal with changed drive (into driver)

but if I give cd /driver ls It gives the proper output of ls in driver directory again comes out of driver directory

Can anybody help me to get terminal with actually changed path (into driver).

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
San
  • 867
  • 3
  • 13
  • 32
  • 1
    Possible duplicate of [Why doesn't "cd" work in a bash shell script?](http://stackoverflow.com/questions/255414/why-doesnt-cd-work-in-a-bash-shell-script) – tripleee Apr 03 '16 at 05:45

5 Answers5

4

If you run your script with

./scriptname

you are opening a sub-shell where the commands of the script are executed. Changing directory in that sub-shell has no effect on the working directory of the shell that you call your script from. If instead you type

source ./scriptname

you should get the desired result.

Thomas Kühn
  • 8,046
  • 3
  • 33
  • 52
2

do "source script_name". It will change the directory

mshriv
  • 332
  • 1
  • 2
1

You could start a shell or terminal in the script, after you set the directory.

as so:

file: driver, remember to set x permission

#!/bin/bash
cd /driver
bash

Running driver will produce another shell prompt.

The current directory is now driver.

Typing "exit" or control-D will go back to the old shell, with its previous directory.

Paul
  • 23,002
  • 11
  • 77
  • 112
1

Your script is an executable file:

#!/bin/sh
cd /driver

remove the #!/bin/sh

cd /driver
tapananand
  • 2,905
  • 2
  • 17
  • 32
Dru
  • 1,306
  • 9
  • 6
0

Just to verify the above problem's root cause you can do the following

Create a script like -

read a
echo "You entered : $a"

Save it (say script.sh) and change the permission accordingly if needed.

In same tab run 'ps' command and note the shell pid (say p1).

Now run the script (i.e. ./script.sh)

Script will ask for the input but don't provide the input. Now in another tab run somthing like 'ps -ef | grep pts'. Here you will find that there are two shell process. You have one more shell whose ppid is equal to the pid of previous shell i.e. p1.

So basically each shell script invocation creates a new process and hence a new context.

Hope this helped.

Sudhansu
  • 160
  • 1
  • 13