LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Shell scripts unable to permanently change directory after exit (https://www.linuxquestions.org/questions/linux-general-1/shell-scripts-unable-to-permanently-change-directory-after-exit-512646/)

ernesto_cgf 12-21-2006 02:32 PM

Shell scripts unable to permanently change directory after exit
 
I need to do a shell script which creates a new directory and changes into it before exiting. I want the shell to be positioned at the newly created directory after the script exits, but when I do the obvious

Code:

mkdir $1
cd $1

and run it, I get my prompt at the original directory.
I googled for this and I only got this, but I do not want to get no for an answer so easily.

uselpa 12-21-2006 02:54 PM

You can use a bash function:
Code:

pu@slackw:~$ mkcs() { mkdir $1 ; cd $1 ; }
pu@slackw:~$ mkcs ttdir
pu@slackw:~/ttdir$


raskin 12-21-2006 02:56 PM

Part one. Explanation of impossibility.

Consider how script is executed. A child process is spawned, and it is bash. It reads the body of the script, and executes one command a time. Then it exits, and its current directory is of no more interest. Parent's working directory is unaffected. And it has to be unaffected. If it was not, any process having child processes would never know what is its working directory. It would mean that the notion of current directory is nonsense.

Part two. Ray of hope.

Let me guess. You use bash and want to automate some action. Then read 'man bash', and edit your .bashrc to add a line:
alias mdcd='mkdir "$1"; cd "$1";'
. Not putting " around $1 will one day bite you...

ernesto_cgf 12-21-2006 03:58 PM

raskin:

I did the

Code:

alias mdcd='mkdir "$1"; cd "$1";'
thing and I got the following

Code:

ernesto@antares:~$ mdcd testdir
mkdir: cannot create directory `': No such file or directory
bash: testdir: command not found

I'm sure this alternative should work someway, but maybe you missed something? Did you try this?

uselpa:

I created your function and it works! I prefer the "mdcd" name though.

Anyway, thanks to you both for the tips. I have my [small] problem solved now. Thanks a lot.

raskin 12-21-2006 04:08 PM

Oops, sorry, certainly it has to be function. Forgot that aliases do not take parameters and that makes them differ from functions.


All times are GMT -5. The time now is 07:34 PM.