0

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"
4
  • 1
    You know, your syntax is not Bash. For example, those aren't bash comments. Commented Feb 11, 2014 at 11:13
  • i edited the "variable a" line. changed to just "a". I need a command like "sh main.sh | grep "delimiter" " Commented Feb 11, 2014 at 11:16
  • just print the variable a only it get the value in main.sh process. Commented Feb 11, 2014 at 11:17
  • no, i cant change the function. Commented Feb 11, 2014 at 11:18

3 Answers 3

3

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.

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

Comments

1

main.sh

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

sub.sh

#!/bin/sh

echo "sub function"
a="get me out of there"
echo "12345"
echo -e "kdsjfkjs"
exit 42

Comments

1

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

Comments

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.