sudo 源:找不到命令

ber*_*436 4 cron

我想以 root 身份运行这个程序。它激活一个虚拟环境并在该虚拟环境中运行一个 python 程序。

该程序看起来像这样

$cat myfile.sh
source /pathto/venv/bin/activate
python /pathto/rsseater.py
Run Code Online (Sandbox Code Playgroud)

如果我只是以 root 身份运行它,我会得到

$ sudo ./myfile.sh 
./myfile.sh: 2: ./myfile.sh: source: not found
Run Code Online (Sandbox Code Playgroud)

我发现了这个,但是如果我尝试添加sudo -s到文件的顶部,它似乎将提示更改为 # - 但 python 没有按预期运行。当我在文件顶部有这样的 sudo -s 时,我不确定程序在做什么。

我怎样才能让这个程序以 root 身份运行?

slm*_*slm 6

您通常希望在脚本顶部添加对解释器的调用,如下所示:

$cat myfile.sh
#!/bin/bash

source /pathto/venv/bin/activate
python /pathto/rsseater.py
Run Code Online (Sandbox Code Playgroud)

这可能看起来与您拥有的非常相似,但实际上非常不同。在您的场景中,您试图在运行时调用 get 的 shell 中运行命令sudo。在上面的示例中,您将获得一个单独的 Bash shell,它将在其中#!/bin/bash调用的行之后具有各种命令。#!/bin/bash导致新的 Bash shell 被分叉。

口译员和shebang

的命名法#!称为shebang。您可以通过本网站维基百科上的各种问答阅读更多相关信息。但可以说,它告诉系统当一个给定的文件被“执行”(又名运行)时,首先从磁盘(解释器)加载一个程序,然后它的任务是解析文件的内容你刚刚执行。

注意:基本上是 shebang 行之后的所有内容。

口译员

解释器是可以一次处理一个文件中的一个命令的任何程序。在这种情况下,我们使用 Bash shell 作为解释器。但是您也可以在此处使用其他 shell,例如 C shell 或 Korne shell。

您也可以以同样的方式使用更高级别的解释器,例如 Perl、Ruby 或 Python。

为什么使用 'sudo -s' 会出错

如果您查看手册页,sudo它会说-s

 -s [command]
            The -s (shell) option runs the shell specified by the SHELL 
            environment variable if it is set or the shell as specified in 
            the password database.  If a command is specified, it is passed
            to the shell for execution via the shell's -c option.  If no 
            command is specified, an interactive shell is executed.
Run Code Online (Sandbox Code Playgroud)

所以当你运行这个命令时:

$ sudo -s ./myfile.sh
Run Code Online (Sandbox Code Playgroud)

发生以下情况:

$ /bin/sh
sh-4.2$ source somesource.bash 
sh: source: somesource.bash: file not found
Run Code Online (Sandbox Code Playgroud)

外壳,/bin/sh不支持命令source.