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 I googled for this and I only got this, but I do not want to get no for an answer so easily. |
You can use a bash function:
Code:
pu@slackw:~$ mkcs() { mkdir $1 ; cd $1 ; } |
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... |
raskin:
I did the Code:
alias mdcd='mkdir "$1"; cd "$1";' Code:
ernesto@antares:~$ mdcd testdir 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. |
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. |