Directory change does not work in shell script

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

#!/bin/sh cd /driver 

The above does not change the directory. Shell works in its own context, so it cannot provide a linux terminal with a modified drive (in the driver)

but if I give cd / driver Ls it gives the correct ls output in the drivers directory again, from the driver directory

Can someone help me get a terminal with a actually changed path (into driver) .

+4
source share
5 answers

If you run your script with

./scriptname

you open a sub shell where script commands are executed. Changing the directory in this sub-shell does not affect the working directory of the shell with which you invoke your script. If instead you type

source ./scriptname

You should get the desired result.

+3
source

make "source script_name". He will change the directory

+1
source

You can run a shell or terminal in a script after installing the directory.

So:

file: driver, don't forget to set x resolution

 #!/bin/bash cd /driver bash 

Running the driver will cause another shell to be called.

The current directory is now a driver.

Entering "exit" or control-D will revert to the old shell with its previous directory.

+1
source

Your script is an executable file:

 #!/bin/sh cd /driver 

delete #!/bin/sh

 cd /driver 
+1
source

To check the above problem, you can do the following

Create a script like -

 read a echo "You entered : $a" 

Save it (say script.sh) and change the resolution if necessary.

In the same tab, run the ps command and pay attention to the shell pid (say p1).

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

Script will ask for input but will not provide input. Now in another tab somthing is launched as' ps -ef | grep pts'. Here you will find that there are two shell processes. You have another shell whose ppid is equal to the pid of the previous shell, i.e. p1.

Thus, basically every shell script call creates a new process and therefore a new context.

Hope this helps.

0
source

Source: https://habr.com/ru/post/1497185/


All Articles