是否可以使用 sudo 或 su 在登录 shell 中运行命令?

是否可以使用 sudo 或 su 在登录 shell 中运行命令?

我正在尝试在登录 shell 中运行非交互式命令(使用su -sudo -i),但到目前为止无法使其工作。

在其中,~/.bashrc我获取了一个脚本,该脚本设置了我的应用程序所需的所有变量。当我进行交互式登录时,su - username我可以看到那里的所有变量,如果我运行我的应用程序,它就可以正常工作。但是,当我尝试使用未设置必要的变量来执行我的应用程序时su - username -c 'command'。换句话说,它似乎su -与选项不兼容-c。 也发生了同样的情况sudo -i -u user command

我搜索了大量问题但找不到这个特定行为的答案。

根据 bash 手册页:

When bash is invoked as an interactive login shell, or as a non-interactive
shell with the `--login` option, it first reads and executes commands from the
file `/etc/profile`, if that file exists. After reading that file, it looks for
`~/.bash_profile`, `~/.bash_login`, and `~/.profile`, in that order, and reads and
executes commands from the first one that exists and is readable. The
`--noprofile` option may be used when the shell is started to inhibit this
behavior.

上述行为无法按~/.profile执行运行~/.bashrc,并且它会反过来提供设置所有变量的脚本。

如何执行非交互式登录 shell?

谢谢

答案1

您可以在脚本中获取变量文件。在脚本中,在引用任何变量之前添加以下行:

source full_path_to_variable_file

这会将您的变量读入脚本的会话中。您必须使用完整的文字路径(无别名),以根目录“/”开头,例如,如果您的主目录的 .bash_aliases 定义了您的变量:

source /home/felima/.bash_aliases

在命令行上 '.' 具有相同的效果

. ~/.bash_aliases

但在脚本中使用“source”更为清晰。

相关内容