如果环境变量未设置,如何记录?

发布于 2024-12-10 16:52:52 字数 45 浏览 0 评论 0原文

如何编写一个 shell 脚本来检查环境变量并在该变量未设置时写入日志文件?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一口甜 2024-12-17 16:52:52

如果您只想在未设置时显示消息,那么:

if [ -z "${CHOSEN_ENV_VAR}" ]
then echo "CHOSEN_ENV_VAR was not set but should have been" >> log.file
fi

如果您只是希望脚本停止并报告 stderr,那么:(

: ${CHOSEN_ENV_VAR:?'was not set but should have been'}

您可以在交互式 shell 中测试它,但交互式 shell 不会退出。将其放入脚本,然后脚本退出。)

If you only want a message when it is unset, then:

if [ -z "${CHOSEN_ENV_VAR}" ]
then echo "CHOSEN_ENV_VAR was not set but should have been" >> log.file
fi

If you simply want the script to stop and report on stderr, then:

: ${CHOSEN_ENV_VAR:?'was not set but should have been'}

(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.)

七七 2024-12-17 16:52:52

写入日志的命令是logger
并且您测试是否使用 test -v 设置了变量,因此在您的脚本中必须具有以下行:

if test ! -v VARNAME; then logger Variable VARNAME is unset; fi

编辑:如果您的意思是 log 只是任意日志文件而不是系统日志,您当然可以用 echo bla bla > 替换记录器日志档案。

The command to write to the log is logger.
And you test if a variable is set with test -v, so in your script you must have the lines:

if test ! -v VARNAME; then logger Variable VARNAME is unset; fi

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

凡尘雨 2024-12-17 16:52:52

[ -z "$name" ] 检查 name 是否为空。要测试它是否未设置,请使用 [ -z "${name+isset}" ]

check() {
  if [ -z "${name+isset}" ]; then
    echo "name is unset"
  elif [ -z "$name" ]; then
    echo "name is empty"
  else
    echo "name is non-empty"
  fi
}
name=me; check name
name=; check name
unset name; check name

[ -z "$name" ] checks whether name is empty. To test whether it is unset, use [ -z "${name+isset}" ].

check() {
  if [ -z "${name+isset}" ]; then
    echo "name is unset"
  elif [ -z "$name" ]; then
    echo "name is empty"
  else
    echo "name is non-empty"
  fi
}
name=me; check name
name=; check name
unset name; check name
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文