Reputation: 935
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)
.
Upvotes: 4
Views: 8420
Reputation: 9810
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.
Upvotes: 4
Reputation: 200
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.
Upvotes: 0
Reputation: 1428
Your script is an executable file:
#!/bin/sh
cd /driver
remove the #!/bin/sh
cd /driver
Upvotes: 1
Reputation: 27423
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.
Upvotes: 1