对不起,我不能给出明确的标题,但这里是简化的问题代码。
#!/bin/bash
# get the absolute path of .conf directory
get_conf_dir() {
local path=$(some_command) || { echo "please install some_command first."; exit 100; }
echo "$path"
}
# process the configuration
read_conf() {
local conf_path="$(get_conf_dir)/foo.conf"
[ -r "$conf_path" ] || { echo "conf file not found"; exit 200; }
# more code ...
}
read_conf
所以基本上这里就是我试图做的是,阅读bash脚本一个简单的配置文件,我有错误处理一些麻烦。
some_command是来自第三方库(即从coreutils的greadlink)获取路径所需的命令。
当运行上面的代码时,我期望它输出“command not found”,因为这是FIRST错误发生的地方,但实际上它总是打印“找不到conf文件”。
我对这样的行为非常困惑,我认为BASH可能意图处理这样的事情,但我不知道为什么。而最重要的是,如何解决它?
任何想法将不胜感激。
也许值得更加明确的消息'请先安装some_command'发送到stdout而不是stderr。以及'get_conf_dir'中的'exit'只能从'$(get_conf_dir)'中的子shell中退出。 – rici
@rici绝对正确。我在那里失去了树林。更新。 –
@林我解决了你的一些问题。并且让你能够正确处理你的'出口100'故障,因为它真的发生了。但是,正如rici指出的那样,你不能在那里退出100退出脚本。它在一个子shell中。查看最新答案中的最后一段。 –