更改父 shell 的目录
我想知道有什么机制可以用来从子 shell 更改父 shell 的目录。例如,我正在 $HOME 中运行脚本“settings.sh”。我的 $HOME 有一个目录 $HOME/TEST/run。如果我的 "settings.sh" 脚本如下所示,
#!/bin/bash
# some shell related code
# some shell related code
cd $HOME/TEST/run
exit 0
我会在 $HOME 的命令提示符处执行上述脚本。执行后,我希望命令提示符位于目录 $HOME/TEST/run 中。我确实明白,在子 shell 中,它被 cd'd 到 $HOME/TEST/run,但在执行结束时,它又回到 $HOME 中。
有没有使用单个脚本执行上述操作的优雅方法。 一种方法是修改脚本“settings.sh”以生成另一个脚本,然后使用“.$HOME/ generatedScript.sh”
I 'm wondering of any mechanism that one could use to change the directory of a parent shell from sub-shell. For ex., I 'm running the script "settings.sh" in my $HOME. My $HOME has a directory $HOME/TEST/run. If my "settings.sh" scripts is as below
#!/bin/bash
# some shell related code
# some shell related code
cd $HOME/TEST/run
exit 0
I execute the above script at command prompt at $HOME. After the execution, I expect my command prompt in directory $HOME/TEST/run. I do understand that in sub-shell, it is being cd'd to $HOME/TEST/run, but at the end of the execution, it's back in $HOME.
Is there any elegant way of doing the above, using a single script. One way is to modify the script "settings.sh" to generate another script and then use ". $HOME/generatedScript.sh"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,你不能。这是设计使然。父进程永远不应该受到子进程结果的影响,除非它们希望受到影响(否则子 shell 可能会对父进程做各种令人讨厌的棘手事情)。
您可以做的是让 shell 将信息保存到文件中或打印目录或...这样父级至少可以使用它来更改目录(如果父级愿意)。
Nope, you can't. That's by design. Parent processes should never be affected by the results of a child without them wanting to be affected (otherwise sub-shells could do all sorts of nasty tricky things to the parent).
What you can do is have the shell save the information into a file or print the directory or ... Such that the parent at least can use it to change directories if the parent wants to.
Wes Hardaker 解释了执行该脚本不会导致其更改父 shell 目录的原因。为了解决此类问题,您必须“获取”脚本而不是执行它。这会导致脚本中的命令在当前 shell 中运行,而不是在子进程中运行。
第一个“.”是一个命令,告诉 shell“获取”指定的文件。以下是
help .
中的文档:Wes Hardaker explained the reasoning behind why executing that script does not cause it to change the directory of the parent shell. In order to work around that type of issue, you must "souce" the script instead of execute it. This causes the commands in the script to run in the current shell, rather than a child process.
The first "." is a command which tells the shell to "source" the specified file. Here is the documentation from
help .
: