开发者

Stay in directory changed after ending of bash script

My bash script:

#!/bin/bas开发者_运维百科h
cd /tmp

Before running my script:

pwd: /

After running my script:

pwd: /

After runnig my script trough sourcing it:

pwd: /tmp

How I can stay at the path from the script without sourcing it ?


You can't. Changes to the current directory only affect the current process.


Let me elaborate a little bit on this:

When you run the script, bash creates a new process for it, and changes to the current directory only affect that process.

When you source the script, the script is executed directly by the shell you are running, without creating extra processes, so changes to the current directory are visible to your main shell process.

So, as Ignacio pointed out, this can not be done


Ignacio is correct. However, as a heinous hack (totally ill advised and this really should get me at least 10 down votes) you can exec a new shell when you're done

#!/bin/bash
...
cd /
exec bash


Here's a silly idea. Use PROMPT_COMMAND. For example:

$ export PROMPT_COMMAND='test -f $CDFILE && cd $(cat $CDFILE) && rm $CDFILE'
$ export CDFILE=/tmp/cd.$$

Then, make the last line of your script be 'pwd > $CDFILE'


If you really need this behavior, you can make your script return the directory, then use it somehow. Something like:

#!/bin/bash
cd /tmp
echo $(pwd)

and then you can

cd $(./script.sh)

Ugly, but does the trick in this simple case.


You can define a function to run in the current shell to support this. E.g.

md() { mkdir -p "$1" && cd "$1"; }

I have the above in my ~/.bashrc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜