Shell Script. How to change to a directory that was assigned to a variable?

Chrono

Diamond Member
Jan 2, 2001
4,959
0
71
For some reason it's not working when I have it in a shell script. Here's an example:

#!/bin/bash

BLAH=/home/whatevers
cd $BLAH


Shouldn't this work? What could be preventing it from working?
 

yelo333

Senior member
Dec 13, 2003
990
0
71
Actually, it did work. But only for the script. The variables revert back to their previous values when you get back to the parent shell. That way, you can cd into a directory in your script, do something, and then not worry about getting back to where you started from.

If you want to keep the cd intact after you exit your script, try running the script with `source myscript.sh` instead of ./myscript.sh or `sh myscript.sh`.

<a target=_blank class=ftalternatingbarlinklarge href="http://www.linuxquestions.org/questions/linux-general-1/cd-keeps-snapping-back-to-current-directory-when-called-from-bash-script-357815/
">Text</a>
 

QED

Diamond Member
Dec 16, 2005
3,428
3
0
Originally posted by: yelo333

If you want to keep the cd intact after you exit your script, try running the script with `source myscript.sh` instead of ./myscript.sh or `sh myscript.sh`.

Or, most succintly ". myscript.sh" (that's a period, space, and then the script name).


 

yelo333

Senior member
Dec 13, 2003
990
0
71
Originally posted by: QED

Or, most succintly ". myscript.sh" (that's a period, space, and then the script name).

Hmm...

$ man bash
[...]
. filename [arguments]
source filename [arguments]
Read and execute commands from filename in the current shell
environment and return the exit status of the last command exe-
cuted from filename. [...]

Cool, thanks for the tip!