gpt4 book ai didi

linux - 每次/bin/sh 被调用时你能运行一个脚本吗?

转载 作者:太空狗 更新时间:2023-10-29 11:08:47 25 4
gpt4 key购买 nike

使用 bash,您可以将 ~/.bashrc 文件设置为在每次创建新的 bash shell 时运行一些东西。是否可以用/bin/sh 做同样的事情? (顺便说一下,这是在 Debian 上)。

现在,我只想在调用/bin/sh 时回显“我是 sh”。这在 bash 中很容易做到(“echo 'I am bash'”位于文件顶部)。

谢谢!

最佳答案

当启动 dash 的登录 shell 时,在类 debian 系统上是 /bin/sh,它将读取 ~/.profile。如果您还想为交互式非登录 shell 读取配置文件,请将以下行添加到您的 ~/.profile 文件中:

ENV=$HOME/.shinit; export ENV

然后,随着变量 ENV 出现在环境中,文件 $HOME/.shinit 将由每个新的交互式(破折号)shell 提供。

您可以将 ENV 指定的文件名更改为您喜欢的任何文件名。

为确保 dash 登录 shell 已将 ENV 添加到环境中,您可能需要注销并重新登录,或者可能需要重新启动,具体取决于您的系统设置。

文档

这在 man dash 中有记录:

A login shell first reads commands from the files /etc/profile and .profile if they exist. If the environment variable ENV is set on entry to an interactive shell, or is set in the .profile of a login shell, the shell next reads commands from the file named in ENV. Therefore, a user should place commands that are to be executed only at login time in the .profile file, and commands that are executed for every interactive shell inside the ENV file.

例子

假设我们的文件设置如下:

$ echo "ENV=$HOME/.shinit; export ENV" >>~/.profile
$ cat .shinit
echo FOUND ME

由于我刚刚将 ENV 行添加到 ~/.profile 文件中,因此 ENV 尚未在环境中。如果我们运行 dash:

$ dash
$

什么都没有发生,因为这是一个非登录 shell 并且 ENV 还不在环境中。

如果我们启动一个登录 shell,ENV 将被放置在环境中并运行 ~/.shinit:

$ dash -l
FOUND ME

如果作为该 shell 的子级,我们运行一个交互式非登录 shell,那么 ~/.shinit 将运行,因为父级 shell 创建了 ENV变量:

$ dash
FOUND ME

上面的登录 shell 创建的环境只影响它的 child 。如上所述,为确保所有交互式 dash shell 在其环境中都有 ENV,可能需要注销并重新登录,或重新启动。

关于linux - 每次/bin/sh 被调用时你能运行一个脚本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26052034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com