maihabunash
maihabunash

Reputation: 1702

Why isn't export working from bash script

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.

Upvotes: 2

Views: 805

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 755064

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

Upvotes: 2

Related Questions