简体   繁体   English

两个shell脚本使用相同的变量

[英]Two shell scripts using same variable

I have two shell scripts test1.sh and test2.sh. 我有两个shell脚本test1.sh和test2.sh。
In test1.sh I have the below statements : 在test1.sh我有以下声明:
In, test1.sh ,I have a variable I whose value will be used by test2.sh 在, test1.sh ,我有一个变量I,其值将由test2.sh使用

#!/bin/sh
I="10"
echo $I

In, test2.sh , the same value of the variable will be copied and printed 在, test2.sh中 ,将复制和打印相同的变量值

#!/bin/sh
J=$I
echo $J

I need to run both the scripts in crontab, I tried export command, but nothing worked. 我需要在crontab中运行这两个脚本,我尝试了导出命令,但没有任何效果。

Add this to you crontab : 将此添加到您的crontab:

. ./test1.sh && ./test2.sh;

And modify you test1.sh like that : 然后修改你的test1.sh:

#!/bin/sh
export I="10"
echo $I

With . 随着. the first will be executed as source and will hold variables. 第一个将作为源执行并将保存变量。

Both scripts are running in their own shell, and only share their environment with their parent process. 这两个脚本都在自己的shell中运行,并且只与其父进程共享其环境。 If you want two separate shell scripts to share environment variables, the variables have to be set (and exported) in the parent process before calling the scripts. 如果需要两个单独的shell脚本来共享环境变量,则必须在调用脚本之前在父进程中设置(和导出)变量。

You could also create a third script that only sets the variables, and source that script from the two main scripts. 您还可以创建仅设置变量的第三个脚本,并从两个主脚本中获取该脚本。

If you want to use the output of test1.sh in script test2.sh , you have two options 如果要在脚本test2.sh使用test1.sh的输出, test1.sh有两个选项

  • store the output of test1.sh in a file and read that file back in test2.sh test1.sh的输出存储在一个文件中,并在test2.sh读回该文件
  • call test1.sh from test2.sh 调用test1.shtest2.sh

test2.sh: test2.sh:

#!/bin/sh
J=$(test1.sh)
echo $J

As @Joachim Pileborg already suggested, you can set (but not echo) variables in one script and source it in the other one 正如@Joachim Pileborg已经建议的那样,您可以在一个脚本中设置(但不回显)变量,并在另一个脚本中将其源化

test1.sh test1.sh

I="10"
J=20
K=30

test2.sh test2.sh

source test1.sh
# do something with I, J, K

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM