一个shell脚本弄清楚不同运行方法的不同

  为了弄清楚shell脚本的运行原理,主要有三种运行方式

 1 #!/usr/bin/bash
 2 echo 'hello world!'                                                       
 3 
 4 echo $admin
 5 
 6 echo $1
 7 echo $0

0、准备工作:

 $ admin="gg"

1、路径执行方式,包括相对路径和绝对路径两种

 $ shellCode/hello.sh  guo

hello world!

guo
shellCode/hello.sh

主要原因是,脚本执行时,重新开启了新的shell进程,由于变量的隔离性,无法获取admin变量的值,所以为空

2、source 调用方式

 $ source shellCode/hello.sh guo 或者

   $ .  shellCode/hello.sh guo 

hello world!
gg
guo
/bin/bash

source方式执行时,直接调用当前shell执行脚本,当然能够获取admin的值为gg了

3、bash命令调用方式

   $ sh shellCode/hello.sh guo 或者

   $ bash  shellCode/hello.sh guo  

hello world!

guo
shellCode/hello.sh

bash方式执行时,打开一个新的子shell执行,无法获取其他shell的变量admin的值gg就对了

第1中和第3中本质上没有什么区别,当赋予了脚本可执行权限时,可以采用第一种和第三种,否则就只能用第二中或第三种。

人就像是被蒙着眼推磨的驴子,生活就像一条鞭子;当鞭子抽到你背上时,你就只能一直往前走,虽然连你也不知道要走到什么时候为止,便一直这么坚持着。
原文地址:https://www.cnblogs.com/guochaoxxl/p/15260943.html