Difference between +x and ./<script> and sh ./<script>

use*_*976 13 command-line chmod

Are there any actual differences between running a script with

[sudo] sh ./<script>.run
Run Code Online (Sandbox Code Playgroud)

instead of

[sudo] chmod +x ./<script>.run
[sudo] ./<script>.run
Run Code Online (Sandbox Code Playgroud)

Flo*_*sch 18

如果你使用

sh ./<script>.run
Run Code Online (Sandbox Code Playgroud)

/bin/sh(通常是 Bourne shell)将用于运行脚本。当然,这只适用于为 Bourne shell 编写的脚本。有时 Linux 的 shell 脚本需要 Bash 而不是 Bourne shell,所以即使它是一个 shell 脚本,这也可能不起作用。

如果你使用

./<script>.run
Run Code Online (Sandbox Code Playgroud)

内核查看shebang 行以找出使用哪个程序来运行该程序。因此,即使它是 Bash、Perl、Python 或其他一些脚本,这也有效。

因此,这通常是运行脚本的首选方式。


Oli*_*Oli 7

As long as it's a sh (Dash, or equivalent) shell script, no, there's no outward difference.

问题是.run不能保证就是这种情况。它可以是二进制的。它可以是 Bash 或 Python 或 PHP 或其他任何东西;他们都有一个shell脚本hash-bang。如果你一味地强行通过sh,谁知道会发生什么。它可能会出错,但它可能会在到达之前意外运行有害代码。

通过chmodding (启用执行权限位)然后运行它./script.run,您可以为其提供最佳的运行可能性。如果它是一个 shell 脚本,它的 hash-bang 将被正确解析,如果它是一个二进制可执行文件,它只会在本地运行。