Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing directory does not work in shell script

Tags:

linux

shell

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).

like image 744
San Avatar asked Feb 16 '23 13:02

San


2 Answers

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.

like image 198
Thomas Kühn Avatar answered Feb 24 '23 06:02

Thomas Kühn


do "source script_name". It will change the directory

like image 25
mshriv Avatar answered Feb 24 '23 06:02

mshriv