如何将自动获取的 shell 脚本写入 /etc/profile

Ale*_*lls 4 bash etc profile

我通过小道消息听说 /etc/profile 中的文件将在登录时由 bash 自动获取?

我尝试向 /etc/profile 写一些简单的东西:

 echo "echo 'foo'" > /etc/profile/foo.sh
Run Code Online (Sandbox Code Playgroud)

但我遇到了这个奇怪的错误:

bash: /etc/profile/foo.sh: Not a directory
Run Code Online (Sandbox Code Playgroud)

有没有正确的方法来做到这一点?

ste*_*eve 10

/etc/profile是一个文件。因此在尝试创建/etc/profile/foo.sh.

/etc/profile.d是您正在考虑的目录。放置在那里的脚本在登录时获取。在您的示例中,您希望创建/etc/profile.d/foo.sh.

这背后的脚本逻辑以及它是如何被引入的,如下所示。类似的代码是/etc/profile/etc/bashrc/etc/csh.cshrc/etc/csh.login

$ grep -A 8 ^for.*profile.d /etc/profile
for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then
            . "$i"
        else
            . "$i" >/dev/null
        fi
    fi
done
$
Run Code Online (Sandbox Code Playgroud)

创建和调用此类脚本的示例:

# echo id >/etc/profile.d/foo.sh
# su - steve
Last login: Sat Jun 23 21:44:41 UTC 2018 on pts/0
uid=1000(steve) gid=1001(steve) groups=1001(steve),4(adm),39(video),1000(google-sudoers) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
$
Run Code Online (Sandbox Code Playgroud)

更多信息见 /etc/profile.d 中的脚本做什么?

  • 这是因为 `sudo echo` 本身获得了提升的权限,而随后的 stdout 重定向仍然以 *original* 权限运行。 (2认同)