Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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.

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
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:



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

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

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

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