shell脚本引用外部变量的两种方法(shell脚本引用变量用法怎么写)没想到

随心笔谈12个月前发布 admin
77 0



本地变量只能在当前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 ?
. https://www.jb51.net/article/subscripts.sh ?
echo -e ${string} ?
exit 0 ?

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

# chmod +x main.sh  

# https://www.jb51.net/article/main.sh  

Hello,World!

注意:

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

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

您可能感兴趣的文章:Shell脚本中引用、调用另一个脚本文件的2种方法Shell脚本中调用、引用、包含另外一个脚本文件的两种方法Shell中调用、引用、包含另一个脚本文件的三种方法

© 版权声明

相关文章