Bash script to change parent shell directory [duplicate]

喜欢而已 提交于 2019-12-01 17:09:59

Use a shell function to front-end your script

setup () {
  # first, call your big script.
  # (It could be open-coded here but that might be a bit ugly.)

  # then finally...

  cd someplace
}

Put the shell function in a shell startup file.

You can technically source your script to run it in your parent shell instead of spawning a subshell to run it. This way whatever changes you make to your current shell (including changing directories) persist.

source /path/to/my/script/script

or

. /path/to/my/script/script

But sourcing has its own dangers, use carefully.

(Peripherally related: how to use scripts to change directories)

Child processes (including shells) cannot change current directory of parent process. Typical solution is using eval in the parent shell. In shell script echo commands you want to run by parent shell:

echo "cd $filepath"

In parent shell, you can kick the shell script with eval:

eval `sh foo.sh`

Note that all standard output will be executed as shell commands. Messages should output to standard error:

echo "Some messages" >&2
command ... >&2

I suppose one possibility would be to make sure that the only output of your script is the path name you want to end up in, and then do:

cd `/path/to/my/script`

There's no way your script can directly affect the environment (including it's current directory) of its parent shell, but this would request that the parent shell itself change directories based on the output of the script...

This can't be done. Use exec to open a new shell in the appropriate directory, replacing the script interpreter.

exec bash
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!