Shell 跨脚本间变量传递
  TEZNKK3IfmPf 2023年11月14日 58 0

Shell 跨脚本变量传递

 

1. source

当前脚本调用另一个脚本变量

$ cat test1.sh
#!/bin/bash
a=Hello World
echo "test1:$a"
$ cat test2.sh
#!/bin/bash
/root/test1.sh
echo " test2:$a"
[root@centos ~]# sh test2.sh
test1:Hello World
test2:

从结果可以看出test1.sh没有把变量a的值传递给test2.sh

我们把test2.sh改成:

#!/bin/bash
source /root/test1.sh
echo "test2:$a"
[root@centos ~]# sh test2.sh
test1:Hello World
test2:Hello World

2 export

当前脚本(第二者脚本)中执行第三者脚本用到第一者脚本中的变量

$ cat test3.sh
#!/bin/bash
echo "test3:$a"

把test2.sh改成:

#!/bin/bash
source /root/test1.sh
echo "test2:$a"
/root/test3.sh

执行test2.sh:

[root@shenji ~]# sh test2.sh
test1:Hello World
test2:Hello World
test3:

将test1.sh改成:

#!/bin/bash
export a=Hello World
echo "test1:$a"

执行test2.sh后有如下结果:

$ sh test2.sh
test1:Hello World
test2:Hello World
test3:Hello World
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   52   0   0 linux服务器
  TEZNKK3IfmPf   2024年05月31日   30   0   0 linux服务器centos
  TEZNKK3IfmPf   2024年05月31日   29   0   0 linuxbind
  TEZNKK3IfmPf   21天前   31   0   0 shell
  TEZNKK3IfmPf   2024年05月31日   40   0   0 linuxshell
TEZNKK3IfmPf