繁体   English   中英

bash 脚本是否在新的 shell 或子 shell 中执行?

[英]Do bash scripts execute in new shells or subshells?

我正在从我的 bash 交互式 shell 运行 bash 脚本:

./shell.sh

我的困惑是,这个脚本会在新的 shell 实例或我当前 bash 实例的子外壳中运行吗? I assume that all shell scripts invoked from a shell run inside a new shell therefore they aren't able to read the local shell variables of the invoking shell. 此外,如果我在调用的脚本中放入“echo $BASH_SUBSHELL”,它会返回一个值“0”,表明它不是子shell。 但是根据一些文章,他们说从 shell 执行 shell 脚本时会调用子shell。 请帮忙。

你是对的; 当您使用./shell.sh运行脚本时,它将在新的 shell 中运行,而不是当前 shell 的子外壳。

它确实在一个子进程中运行,即 shell,所以说“子进程+shell=子shell,所以它必须是子shell”是一个诱人且常见的错误。 但这是不正确的。 The shell running the script won't inherit shell variables from the parent shell process (it'll inherit environment variables, ie export ed variables, but that's true of any subprocess), it won't inherit shell modes (eg set -e ) or other shell state, and it won't even necessarily be running the same shell (if you're running bash and the script has a #!/bin/zsh shebang, it'll run in zsh). 因此,它在逻辑上是一个不同的 shell 恰好作为启动它的 shell 的子进程运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM