【问题标题】:MacOSX how to autorun a script after su - root?MacOS如何在su - root后自动运行脚本?
【发布时间】:2013-02-04 04:22:49
【问题描述】:

假设我是普通用户,我将切换到root:

user ~ $ su - root
Password: 
root ~ #

所以一旦我以root 登录,我希望自动运行以下命令

source .bash_profile

请问如何让above command 自动运行?

【问题讨论】:

    标签: macos root .bash-profile


    【解决方案1】:

    根据 bash 手册页,.bash_profile 用于登录 shell,而.bashrc 用于交互式非登录 shell。

    在您的情况下,您不需要像这样获取.bash_profile

    您只需将source .bash_profile 放入根目录的.bashrc 文件中

    if [ -f ~/.bash_profile ]; then
       source ~/.bash_profile
    fi
    

    阅读me 以更好地理解.bash_profile.bashrc

    更新

    例子:

    [root@sgeorge-ld ~]# cat .bashrc | tail -1
    echo "Testing .bashrc for a stack query"
    [root@sgeorge-ld ~]# exit
    logout
    [sgeorge@sgeorge-ld ~]$ su - root
    Password: 
    Testing .bashrc for a stack query
    [root@sgeorge-ld ~]# 
    

    【讨论】:

    • 不受影响。我需要重新启动一些东西吗?
    • 没有。你不需要重新启动任何东西.. 你确定你有~/.bash_profile 吗?
    • hmm.. 所以你把这个if 条件放在/root/.bashrc 中。对吗?
    • 是的。然后,我来自普通用户的su -。然后当我变成root时,什么都没有发生。
    • "终端窗口指南的一个例外是 Mac OS X 的 Terminal.app,它默认为每个新终端窗口运行一个登录 shell,调用 .bash_profile 而不是 .bashrc。其他 GUI 终端模拟器可能做同样的事情,但大多数人倾向于不这样做。”。那么你可以尝试使用.bash_profile 而不是.bashrc
    【解决方案2】:

    首先,当您切换到 root 用户时,您仍将是您的普通用户的主目录。您要执行哪个 .bash_profile? /Users/myuser/.bash_profile 还是 root 的 /var/root/.bash_profile?

    无论你想执行什么,你都可以编辑 /var/root/.bashrc(如果你没有,创建一个)并在那里添加你的命令。

    【讨论】:

    • 您好,现在我将echo 'hello' 添加到:/var/root/.bash_profile/var/root/.bashrc 作为根。但是当我su - root 再次进入里面时,什么都没有发生!
    • su - root代替sudo -s
    • 顺便问一下,你用的是哪个shell? root 的默认 shell 是 /bin/sh。我使用/bin/bash。为此,您可以编辑/etc/passwd 文件。或者,如果你想继续使用 /bin/sh,而不是 /var/root/.bash_profile,你需要 /var/root/.profile
    • 不,OS X Terminal 是一个终端模拟器。 Shell 是命令解释器。如果你输入echo $SHELL,你会看到你的shell是什么。
    • 也可以这样做:编辑/var/root/.profile,添加echo "hello",然后不使用su - root,而是使用sudo -s。它会起作用的。
    猜你喜欢
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 2021-10-26
    • 2020-10-05
    相关资源
    最近更新 更多