2

I have a .sh (start_sim.sh) and a .bash (sim_sources.bash) file. The sim_sources.bash file is called from within the start_sim.sh and should set an environment variable $ROBOT to a certain value. However the ROBOT variable never changes when I call ./start_sim.sh. Is there a fundamental mistake in the way I am trying to do this?

start_sim.sh contains:

#!/bin/bash

echo -n "sourcing sim_sources.bash..."
source /home/.../sim_sources.bash
echo "done."

sim_sources.bash contains:

# set the robot id
export ROBOT=robot

EDIT: Could you also propose a way to work around this issue? I would still need to set variables from with in the .bash file.

EDIT2: Thanks for your replys! Finally I ended up solving it with a screen and stuffing commands to it:

echo -n "starting screen..."
screen -dmS "sim_screen"
sleep 2
screen -S "sim_screen" -p 0 -X stuff "source /home/.../sim_sources.bash$(printf \\r)"
sleep 5
screen -S "sim_screen" -p 0 -X stuff "source /home/.../start_sim.sh$(printf \\r)"
0

3 Answers 3

6

You're setting the ROBOT variable in the start_sim.sh script, but that's not available to parent processes (your spawning shell/command-prompt).

Exporting a variable e.g. export ROBOT=robot makes the variable available to the current process and child processes. When you invoke ./start_sim.sh you're invoking a new process.

If you simply source start_sim.sh in your shell, that script runs as part of your shell process and then your variable will be available.

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

1 Comment

Thanks for your hint. But is there any way to work around this? I would need to set the variable from within the script. (There are actually a whole bunch of variables which should be set from the .bash file - however until now source has been called from within the .bashrc).
4

As Brian pointed out the variables are not available outside of the script.

Here a adapted script that shows this point:

#!/bin/bash

echo -n "sourcing sim_sources.bash..."
. sim_sources.bash
echo $ROBOT
echo "done."

The workaround you are asking for is to start a new shell from the actual shell with the environmental values already set:

#!/bin/bash

echo -n "sourcing sim_sources.bash..."
. sim_sources.bash
echo "done."
bash

This results in:

bash-4.1$ printenv | grep ROBOT
ROBOT=robot

Comments

0

I am on Ubuntu 16.04

I used /bin/sh instead of /bin/bash and it works !

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.