bash 打印错误信息的正确方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12700507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:26:25  来源:igfitidea点击:

Proper way of printing out an error message

bash

提问by Robottinosino

Is this line the best way to print out an error message in Bash?

这行是在 Bash 中打印错误消息的最佳方式吗?

echo 'Error: banana' >&2

I need to update tens of Bash scripts which use all different ways of logging errors and I might as well choose the "right" way to do this and adhere to a standard as I do it...

我需要更新数十个使用所有不同方式记录错误的 Bash 脚本,我不妨选择“正确”的方式来做到这一点,并在我做的时候遵守标准......

采纳答案by sehe

On linux, I'd prefer to say

在 linux 上,我更愿意说

echo "Some error message" >> /dev/stderr

This will effectively do the same, of course, since /dev/stderrsymlinks to /proc/$PID/fd/2

当然,这将有效地做同样的事情,因为/dev/stderr符号链接到/proc/$PID/fd/2

回答by uml?ute

at the beginning of my bash-scripts i usually define some functions like:

在我的 bash 脚本开始时,我通常定义一些函数,例如:

error() {
  echo "$@" 1>&2
}

fail() {
  error "$@"
  exit 1
}

which comes quite handy for outputting deadly and ordinary errors. you could move this snippet into a separate file and sourcethat from your all of your bash-scripts with something like:

这对于输出致命和普通错误非常方便。您可以将此代码段移动到一个单独的文件中,并source从您所有的 bash 脚本中使用以下内容:

. /usr/local/lib/snippets/error_handling.sh

so whenever you decide you need a better way to deal with error messages (e.g. sending critical errors to syslog), you can do so by changing the behaviour for all scripts in one go.

因此,无论何时您决定需要一种更好的方法来处理错误消息(例如,将严重错误发送到系统日志),您都可以通过一次性更改所有脚本的行为来实现。