简体   繁体   中英

Two shell scripts using same variable

I have two shell scripts test1.sh and test2.sh.
In test1.sh I have the below statements :
In, test1.sh ,I have a variable I whose value will be used by test2.sh

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

In, test2.sh , the same value of the variable will be copied and printed

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

I need to run both the scripts in crontab, I tried export command, but nothing worked.

Add this to you crontab :

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

And modify you test1.sh like that :

#!/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. 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.

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

  • store the output of test1.sh in a file and read that file back in test2.sh
  • call test1.sh from 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

test1.sh

I="10"
J=20
K=30

test2.sh

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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