LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   cd inside if than statement, after fi back to old dir (https://www.linuxquestions.org/questions/linux-newbie-8/cd-inside-if-than-statement-after-fi-back-to-old-dir-819457/)

dukedog 07-12-2010 03:04 PM

cd inside if than statement, after fi back to old dir
 
the script below prints the pwd of where I want to be. after the fi it puts me back at the original dir. just writing these scripts to understand what's going on.


#! /bin/bash
if
[ -d mydir ]
then
cd mydir/ && pwd
fi

thanks again for the great www.site

tredegar 07-12-2010 03:44 PM

Hmmmm, I remember something about this.... It is (a little) complicated.

Maybe best to try a search on bash function cd to find some explanations about just why this is happening.

HTH

David the H. 07-12-2010 04:10 PM

Is this actually a question? ;)

If you're running this as a stand-alone script, then the shell forks a separate process for it, and all actions taken (other than echoing to stdout) only affect that subshell. Since no sub-process can change the environment of its parent, once the script exits, its local environment is lost and you're back where you started.

If you run the command directly from the command line, or set and run it as a function in the current shell, then it will be executed inside the current process, and will leave you in that directory.

smeezekitty 07-12-2010 04:51 PM

http://www.google.com/url?sa=t&sourc...ulmIp9g1I3Ma4Q

dukedog 07-12-2010 08:16 PM

thanks for the info. Yes that actually was a question, for us Newbie's sometimes we have to ask dumb questions to understand. Thanks again David the great for your explanation, I though there might be something like that going on but wasn't sure


All times are GMT -5. The time now is 06:10 AM.