Export command - variable

Hello,
Please see the script found in my computer below. (Ubuntu 14.04)

#!/bin/sh
export APP_DIR="/home/appname"
monitorscript="$APP_DIR""/monitor.sh"
ps cax | grep monitor.sh > /dev/null
if [ $? -eq 0 ]; then
echo "monitor.sh is running"
else
"$monitorscript"
fi

My question is regarding EXPORT command
I know everybody has their own style on coding but I wonder why do we use EXPORT to assign/call a variable to monitorscript variable?

Thank you
Boris

Unless the variable APP_DIR is referenced inside /home/appnam/monitor.sh , export is not needed.

So in that case you could just use this instead:

#!/bin/sh
APP_DIR=/home/appname
[..]
1 Like

The export keyword will make a variable visible in child processes of the process it is set in. Example: processA has a variable X=something. If processA starts a child processB the variable X will evaluate to "" (empty string) because this is a new process. The same goes for a processC started as child of processB and so on. If the variable is exported this makes no difference for processA but it will show up in processBs environment too.

Since you start one process from this process, namely:

else
"$monitorscript"
fi

The variable APP_DIR will be part of the environment of the started monitor-script because of the export . Without the export it would not. That has nothing to do with "style", maybe the process needs this variable set (i don't know). If not, then the export is superfluous and a simple:

APP_DIR="/home/appname"

would also suffice.

On a side note, this:

ps cax | grep monitor.sh > /dev/null
if [ $? -eq 0 ]; then
echo "monitor.sh is running"
else
"$monitorscript"
fi

would be better written this way:

if ps cax | grep -q 'monitor.sh' ; then
     echo "monitor.sh is running"
else
     "$monitorscript"
fi

I hope this helps.

bakunin

2 Likes

@Scrutinizer, Thank you so much.
@Bakunin, Thank you for your detailed explanation. While checking that script, I just wondered that. Got the difference which you implied now.

Kind regards
Boris