首页 > Linux教程 > 正文

执行Shell脚本的4种方法及区别详解

执行shell脚本有以下几种方式

1、相对路径方式,需先cd到脚本路径下

[root@pythontab.com tmp]# cd /tmp  
[root@pythontab.com tmp]# ./pythontab.sh

2、绝对路径方式

[root@pythontab.com tmp]# /tmp/pythontab.sh

3、bash命令调用

[root@pythontab.com /]# bash /tmp/pythontab.sh

4、. (空格)  相对或绝对方式

[root@pythontab.com /]# . /tmp/pythontab.sh   

几种方式的区别

第一种和第二种没有什么区别,两种方式都需要提前赋予脚本以执行权限。

第三种是把脚本当做bash的调用来处理,所以,脚本不需要有执行权限就可以执行。

前三种方式都是在当前shell中打开一个子shell来执行脚本内容,当脚本内容结束,则子shell关闭,回到父shell中。

第四种是使脚本内容在当前shell里执行,而不是单独开子shell执行。

开子shell与不开子shell的区别就在于,环境变量的继承关系,如在子shell中设置的当前变量,不做特殊通道处理的话,父shell是不可见的。

而在当前shell中执行的话,则所有设置的环境变量都是直接生效可用的。

验证:

[root@pythontab.com /]# cat /tmp/pythontab.sh   
top

1、前三种执行方式下的pstree显示

├─sshd─┬─sshd───bash───bash───top  
│      └─sshd───bash───pstree

2、第四种执行方式下的pstree显示

├─sshd─┬─sshd───bash───top  
│      └─sshd───bash───pstree

3、验证环境变量设置的继承关系及可见关系

建立两个脚本,father.sh和subshell.sh。其中father.sh调用subshell.sh

[root@pythontab.com /]# cat /tmp/father.sh 
v_ceshi='father'
#-------父shell中定义变量
echo "以子shell方式调用脚本"
/tmp/subshell.sh
echo "输出v_ceshi值为${v_ceshi}"
echo ""
echo "在当前shell中执行脚本"
. /tmp/subshell.sh
echo "输出v_ceshi值为${v_ceshi}"

[root@pythontab.com /]# 

[root@pythontab.com /]# cat /tmp/subshell.sh 
v_ceshi=son

[root@pythontab.com /]# 

执行结果为

[root@pythontab.com /]# /tmp/father.sh 
以子shell方式调用脚本
输出v_ceshi值为father
在当前shell中执行脚本
输出v_ceshi值为son


上一篇:linux下两台服务器文件实时同步方案实现
下一篇:如何确保Linux系统干净的三个须知

PythonTab微信公众号:

Python技术交流互助群 ( 请勿加多个群 ):

群1: 87464755

群2: 333646237

群3: 318130924

群4: 385100854