shell脚本引用外部变量的两种方法

本地变量只能在当前bash进程中有效,对当前shell之外的其它进程,包括子进程均无效。而启动脚本实际就是开启一个子进程执行命令,所以,在脚本里就无法引用父进程上的本地变量。如下,

引用外部变量失败:

[root@centos7 test]#echo $var
yes
[root@centos7 test]#bash test.sh 
[root@centos7 test]#

那如何在脚本中引用外部变量呢,有两种方法可以实现

第一种:把变量设置成环境变量

[root@centos7 test]#export var
[root@centos7 test]#bash test.sh 
yes
[root@centos7 test]#

第二种:用source方式启动脚本(或者用. /path/name.sh;注意点号和斜杠之间必须有空格,若没有空格就是直接执行脚本,是不一样的),这种方式不会开启子进程,而是把脚本加载到当前进程中执行,所以也就能引用当前进程中的本地变量了。

[root@centos7 test]#newvar="no"
[root@centos7 test]#source test.sh 
no
[root@centos7 test]#. test.sh 
no
[root@centos7 test]#

举例

假设有如下两个脚本:

main.sh           #主脚本
subscripts.sh     #子脚本,或者说被调脚本 

subscripts.sh 脚本内容如下:

#! /bin/bash  
string="Hello,World! \n"

main.sh 脚本(引用 subscripts.sh 脚本的变量)内容如下:

#! /bin/bash  
. ./subscripts.sh  
echo -e ${string}  
exit 0  

运行 mian.sh 脚本输出结果:

# chmod +x main.sh  
# ./main.sh  
Hello,World!

注意:

  • 被调脚本可以没有执行权限,调用脚本必须有可执行权限。
  • 上述例子中是变量的引用,函数的引用也是一样的流程。

 到此这篇关于shell脚本引用外部变量的两种方法的文章就介绍到这了,更多相关shell 引用外部变量内容请搜索aitechtogether.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持aitechtogether.com!

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2023年7月6日
下一篇 2023年7月6日

相关推荐