Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run 'cd' in shell script and stay there after script finishes?

Tags:

bash

shell

cd

pwd

I used 'change directory' in my shell script (bash)

#!/bin/bash alias mycd='cd some_place' mycd pwd 

pwd prints some_place correctly, but after the script finished my current working directory doesn't change.

Is it possible to change my path by script?

like image 590
qrtt1 Avatar asked Oct 07 '10 07:10

qrtt1


People also ask

Can we use cd command in shell script?

Trying to use cd inside the shell script does not work because the shell script runs in the subshell and once the script is over it returns to the parent shell, which is why the current directory does not change.

How do you continue a script?

CONT'D (an abbreviation for continued) should be written next to the character's name to indicate that their speech is continued.


1 Answers

You need to source the file as:

. myfile.sh 

or

source myfile.sh 

Without sourcing the changes will happen in the sub-shell and not in the parent shell which is invoking the script. But when you source a file the lines in the file are executed as if they were typed at the command line.

like image 129
codaddict Avatar answered Sep 23 '22 07:09

codaddict