Reputation: 938
I've got two sh files, which are "main.sh" and "sub.sh" i want to return a variable's value inside "sub.sh" and use it inside main.sh .There is so many "echo" command so i can't just return the value from sub.sh file. I need only one variable's value. How can that be possible?
main.sh
echo "start"
//how to get a variable from the sh below?
//dene=$(/root/sub.sh)
echo "finish"
sub.sh
echo "sub function"
a="get me out of there" // i want to return that variable from script
echo "12345"
echo "kdsjfkjs"
Upvotes: 0
Views: 555
Reputation: 1387
You can export variable to shell session in sub.sh and catch it later in main.sh.
sub.sh
#!/usr/bin/sh
export VARIABLE="BLABLABLA"
main.sh
#!/bin/sh
. ./sub.sh
echo $VARIABLE
Upvotes: 1
Reputation: 16253
#!/bin/sh
echo "start"
# Optionally > /dev/null to suppress output of script
source /root/sub.sh
# Check if variable a is defined and contains sth. and print it if it does
if [ -n "${a}" ]; then
# Do whatever you want with a at this point
echo $a
fi
echo "finish"
#!/bin/sh
echo "sub function"
a="get me out of there"
echo "12345"
echo -e "kdsjfkjs"
exit 42
Upvotes: 1
Reputation: 249153
To "send" the variable, do this:
echo MAGIC: $a
To "receive" it:
dene=$(./sub.sh | sed -n 's/^MAGIC: //p')
What this does is to discard all lines that don't start with MAGIC: and print the part after that token when a match is found. You can substitute your own special word instead of MAGIC.
Edit: or you could do it by "source"ing the sub-script. That is:
source sub.sh
dene=$a
What that does is to run sub.sh
in the context of main.sh
, as if the text were just copy-pasted right in. Then you can access the variables and so on.
Upvotes: 3