Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How can I write a shell script that checks for an environment variable and writes to a log file if the variable is unset?

Also, if the file name pointed by env variable doesn't exist, how to create it?

share|improve this question
    
also asked in stackoverflow –  glenn jackman Oct 19 '11 at 13:54
    
Thanks for copying my edit and cross-posting it on SO...anyway, you accepted an answer there and not here, so I'm going to close this version –  Michael Mrozek Oct 19 '11 at 13:57
add comment

closed as too localized by Michael Mrozek Oct 19 '11 at 13:57

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers

up vote 4 down vote accepted

An environment variable is one that is exported to subprocesses.
This script, yet to adapt to your need, could be of help. It uses the ${var:?word} syntax, with and without : to determine the result:

#!/bin/sh

unset=0
null=0

if ! sh -c 'echo ${var?}' >/dev/null 2>/dev/null; then
   unset=1
elif ! sh -c 'echo ${var:?}' >/dev/null 2>/dev/null; then
   null=1
fi

echo "unset = $unset"
echo "null  = $null"
share|improve this answer
    
@enzo: An excellent clear answer which addresses the unset issue very well, and deals the associated script abort (+1).. I really needed something like this today; thanks.. It seems that I must first export the var in question (makes sense), and whether it is set or not, it is still detected appropriately in the sub-shell. very nice! ..One point of note is that is isn't possible to export arrays, (which is specifically what I was after :) but for non-array vars, it will definitely come in handy.. The method handles arrays in the current process, but will abort when var is not set/null. –  Peter.O Oct 23 '11 at 12:38
add comment

if i understand you rightly,

env | grep -q ^$VAR && logger -t varlogger "var is unset"

test -f $VAR || touch $VAR

share|improve this answer
    
You'll want to grep for ^$VAR= since just ^$VAR can match several variables that start with the same thing. You can also just test $VAR && logger.... –  Shawn J. Goff Oct 19 '11 at 11:15
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.