1

I have a shell script that generates and runs a shell script. I need to get hold of a variable that is set once the generated script is run. testVar script:

#!/bin/bash

echo "#!/bin/bash" > testGen
echo "somePid='12345' # this is actually set by a program" >> testGen
echo "echo \"somePid set to: \${somePid}\"" >> testGen

/bin/bash ./testGen  # execute the generated script

echo "somePid after exec: ${somePid}" # how to get the ${somePid}?

How can I get ${somePid} ? Expected output:

$ ./testVar
somePid set to: 12345
somePid after exec: 12345
2
  • 1
    You would have to source the other script (or use the equivalent . command), so it runs in the same shell. But... why create another script rather than just executing commands directly? It seems like an overcomplicated and fragile way to do things. Commented Apr 16, 2020 at 0:32
  • Thanks Gordon! . ./testgen works. This is a simplified example, the actual script for computational fluid dynamics is large, and dictates this scenario Commented Apr 16, 2020 at 1:11

2 Answers 2

2
  1. first of all, you can store process id in file, in Linux it is very popular idea to store pid to PIDFILE ( file.pid ). Many linux processes do that, storing their pidfiles in /var/run or in /tmp. Then you can read pid from the file using cat command

  2. You can run other script using "." or "source" command - in this case other script will be executed in the same shell process, and any variables which will set by other script will be avalable after completion

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

1 Comment

Thank you, checking this as the accepted answer. I was aware of storing the pid file, but was looking for a simpler way. I forgot about the "source" command. For others: In above example, replace: /bin/bash ./testGen with: . ./testGen
0

You could store the PID in a file, for instance

# This is in your testVar
echo 'echo $somePid >somePid' >> testGen

After running your program, you can retrieve it from there:

./testVar
echo "somePid after exec: $(<somePid)"

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.