不同方式运行shell脚本的区别

不同方式运行shell脚本的区别

本文介绍了不同方式运行shell脚本的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近有人问我一个问题.执行shell脚本有哪些不同的方式,每种方式的区别是什么?

我说我们可以在下面的方法中运行shell脚本,假设test.sh是脚本名称,

  1. sh test.sh
  2. ./test.sh
  3. ../test.sh

我不知道 1 & 之间的区别2. 但通常在前 2 个方法中,在执行时,它会产生新进程并运行相同的进程.而在最后一种方法中,它不会产生新进程.相反,它在同一个中运行.

如果我错了,有人可以对此提出更多见解并纠正我吗?

解决方案
sh test.sh

告诉命令使用sh来执行test.sh.

./test.sh

告诉命令执行脚本.解释器需要在第一行定义,例如 #!/bin/sh#!/bin/bash.注意(感谢 keltar) 在这种情况下,文件 test.sh 需要对执行此命令的用户具有执行权限.否则不会被执行.

在这两种情况下,所有使用的变量都会在脚本执行后过期.

../test.sh

获取代码.也就是说,它执行它并且执行的任何内容、定义的变量等都将保留在会话中.

更多信息,您可以查看执行 bash 脚本和获取 bash 脚本有什么区别? 很好的答案:

区别在于:

  • 当您执行脚本时,您正在打开一个 shell,输入新 shell 中的命令,将输出复制回当前壳,然后关闭新壳.环境的任何变化都需要仅在新外壳中有效,一旦新外壳消失关闭.

  • 当您source脚本时,您正在输入您的命令当前外壳.对环境的任何更改都将生效并保留在您当前的 shell 中.

Recently I have been asked a question. What are the different ways of executing shell script and what is the difference between each methods ?

I said we can run shell script in the following methods assuming test.sh is the script name,

  1. sh test.sh
  2. ./test.sh
  3. . ./test.sh

I don't know the difference between 1 & 2. But usually in first 2 methods, upon executing, it will spawn new process and run the same. Whereas in the last method, it won't spawn new process. Instead it runs in the same one.

Can someone throw more insight on this and correct me if I am wrong?

解决方案
sh test.sh

Tells the command to use sh to execute test.sh.

./test.sh

Tells the command to execute the script. The interpreter needs to be defined in the first line with something like #!/bin/sh or #!/bin/bash. Note (thanks keltar) that in this case the file test.sh needs to have execution rights for the user performing this command. Otherwise it will not be executed.

In both cases, all variables used will expire after the script is executed.

. ./test.sh

Sources the code. That is, it executes it and whatever executed, variables defined, etc, will persist in the session.

For further information, you can check What is the difference between executing a bash script and sourcing a bash script? very good answer:

这篇关于不同方式运行shell脚本的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 03:45