1

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.

2
  • 1
    Are the two scripts running separately, or are you calling one from the other? In which order are the scripts called? Commented Feb 18, 2013 at 10:29
  • They are two different scripts, firstly test1.sh is called and then the test2.sh is called. Commented Feb 18, 2013 at 10:31

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

2 Comments

If I have more than one variable, how should I write the code.
@Vishu Joachim Pileborg already suggested sourcing the script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.