“./"之间的区别和“sh"在 UNIX 中 [英] Difference between "./" and "sh" in UNIX
问题描述
有时我看到很少有脚本是通过sh"命令执行的,有时是通过./"命令执行的.我无法理解它们之间的确切区别.请帮帮我.
Sometimes i see that few scripts are executed through "sh" command and sometimes through "./" command.I am not able to understand the exact difference between them.Please help me out .
推荐答案
sh file
在新的 shell 进程中执行 shell-script 文件.
sh file
executes a shell-script file in a new shell process.
<代码>.file 在当前 shell 进程中执行一个 shell-script 文件.
. file
executes a shell-script file in the current shell process.
./file
将执行当前目录中的文件.该文件可以是二进制可执行文件,也可以以 hashbang 行开头(文件的第一行格式为 #!....
,例如 #!/usr/文件中的 bin/ruby
表示脚本需要作为 Ruby 文件执行).该文件需要设置可执行标志.
./file
will execute the file in the current directory. The file can be a binary executable, or it can start with a hashbang line (the first line of the file in form of #!....
, for example #!/usr/bin/ruby
in a file would signify the script needs to be executed as a Ruby file). The file needs to have the executable flag set.
例如,如果您有脚本 test.sh
:
For example, if you have the script test.sh
:
#!/bin/sh
TEST=present
并且你用 sh test.sh
执行它,你会启动一个新的 sh
(或者更确切地说 bash
,最有可能的,作为在现代系统中,一个与另一个软链接),然后在其中定义一个新变量,然后退出.随后的 echo $TEST
打印一个空行 - 变量未在外壳中设置.
and you execute it with sh test.sh
, you'd launch a new sh
(or rather bash
, most likely, as one is softlinked to the other in modern systems), then define a new variable inside it, then exit. A subsequent echo $TEST
prints an empty line - the variable is not set in the outer shell.
如果您使用 启动它.test.sh
,您将使用当前 shell 执行脚本.echo $TEST
的结果将打印 present
.
If you launch it using . test.sh
, you'd execute the script using the current shell. The result of echo $TEST
would print present
.
如果你使用 ./test.sh
启动它,第一行 #!/bin/sh
将被检测到,那么它就像你写的一样/bin/sh ./test.sh
,在这种情况下归结为第一种情况.但是,如果 hashbang 行是,例如,#!/usr/bin/perl -w
,则该文件将使用 /usr/bin/perl -w ./test 执行.sh
.
If you launch it using ./test.sh
, the first line #!/bin/sh
would be detected, then it would be exactly as if you wrote /bin/sh ./test.sh
, which in this case boils down to the first scenario. But if the hashbang line was, for example, #!/usr/bin/perl -w
, the file would have been executed with /usr/bin/perl -w ./test.sh
.
这篇关于“./"之间的区别和“sh"在 UNIX 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!