NickName:xyz Ask DateTime:2011-10-19T14:15:28 How to log if an environment variable is unset? How can I write a shell script that checks for an environment variable and writes to a log file if the variable is unset? Copyright Notice:Content Author:「xyz」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.Link to original article:https://stackoverflow.com/questions/7817267/how-to-log-if-an-environment-variable-is-unset Answers flolo 2011-10-19T06:23:01 The command to write to the log is logger.\nAnd you test if a variable is set with test -v, so in your script you must have the lines:\n\nif test ! -v VARNAME; then logger Variable VARNAME is unset; fi\n\n\nEDIT: In case you mean with log just an arbitrary log file and not the system log, you can of course replace the logger with echo bla bla > log.file.", Jonathan Leffler 2011-10-19T06:23:45 If you only want a message when it is unset, then:\n\nif [ -z \"${CHOSEN_ENV_VAR}\" ]\nthen echo \"CHOSEN_ENV_VAR was not set but should have been\" >> log.file\nfi\n\n\nIf you simply want the script to stop and report on stderr, then:\n\n: ${CHOSEN_ENV_VAR:?'was not set but should have been'}\n\n\n(You can test that in an interactive shell, but the interactive shell won't exit. Put it in a script and the script is exited.)",