2

Why isn't exporting a variable working in the following case:

In the following example I export the PARAM variable and set the sleep to 1000 second in order to run the script as process on the background.

#!/bin/bash

export PARAM="I AM A REAL VALUE"

sleep 1000

so I execute the script as process as the following:

 /tmp/example.bash &

Now script runs as a process (I checked it with ps -ef) and from the Linux console I want to print the $PARAM as the following

 echo $PARAM

but no value from PARAM variable.

Why? The export from the script isn’t exporting the value when the script process is running.

5
  • because your script spawns a new child shell and then you go back to parent shell and check for variable. Commented May 12, 2015 at 6:10
  • You are running the script under subshell. subshell cannot change parent shell environment (not without any hack at least.) You need to source it. Commented May 12, 2015 at 6:10
  • so what is the way to print the vars from the console ? or from other script Commented May 12, 2015 at 6:15
  • Use the . command or (in Bash or C shells) the source command to read the file. OTOH, you probably don't want to wait over 15 minutes to see the results; lose the sleep 1000. Commented May 12, 2015 at 6:17
  • hi please write your answer , so I will can vote for your solution Commented May 12, 2015 at 6:20

1 Answer 1

2

When you run /tmp/example.bash &, you set the environment in the sub-shell, but that does not affect the parent shell that ran it.

You need to (a) remove the sleep 1000 and (b) use the . command or (in Bash or a C shell) the source command to read the file as part of the current process:

sed -i.bak '/sleep/d' /tmp/example.bash  # GNU or BSD sed
. /tmp/example.bash
echo $PARAM
Sign up to request clarification or add additional context in comments.

2 Comments

you shuld write this . ./tmp/example.bash ( you forget the "." )
There isn't a . in front of /tmp/example.bash in the question, so it is not I who forgot the leading dot. But fixing a file name to match your local requirements is hardly rocket science; it is pretty much assumed in any SO answer where files are used — reworking the names to meet the actual location names is necessary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.