我有一个检查环境的脚本,我想问您有关如何处理“找不到命令”错误的建议。
if (_Size == 2)
return operator[](0) * operator[](3) - operator[](2) * operator[](1);
它显示echo "...RVM Version : $(rvm -v)"
echo "...Node Version : $(node -v)"
echo "...Ruby Version : $(ruby -v)"
echo "...Bundler Version : $(bundle -v)"
echo "...Passenger Version: $(passenger -v)"
和node
命令的“找不到命令”:
passenger
我不想显示错误,而是显示“未找到”,就像这样:
...RVM Version : rvm 1.29.7 (latest) by Michal Papis
deploy_confirm.sh: line 10: node: command not found
...Node Version :
...Ruby Version : ruby 2.6.0p0 (2018-12-25 revision 66547)
...Bundler Version : Bundler version 2.0.1
deploy_confirm.sh: line 13: passenger: command not found
...Passenger Version:
答案 0 :(得分:4)
使用2>/dev/null
禁止显示错误消息,并使用||
作为else
的简写。如果命令a || b
失败,b
将运行a
。
echo "...Login Shell User : $(whoami)"
echo "...RVM Version : $(rvm -v 2>/dev/null || echo 'Not found')"
echo "...Node Version : $(node -v 2>/dev/null || echo 'Not found')"
echo "...Ruby Version : $(ruby -v 2>/dev/null || echo 'Not found')"
echo "...Bundler Version : $(bundle -v 2>/dev/null || echo 'Not found')"
echo "...Passenger Version: $(passenger -v 2>/dev/null || echo 'Not found')"
答案 1 :(得分:3)
包装器功能是一种获得自定义行为的简便方法,特别是在不希望在全局范围内更改行为的情况下(尤其是)。
or_not_found() {
if type "$1" >/dev/null 2>&1; then # if given a valid command
"$@" # run that command with original arguments
else
echo "Not found" # write to stdout so it's captured by the command substitution
fi
}
echo "...Login Shell User : $USER" # much more efficient than calling whoami
echo "...RVM Version : $(or_not_found rvm -v)"
echo "...Node Version : $(or_not_found node -v)"
echo "...Ruby Version : $(or_not_found ruby -v)"
echo "...Bundler Version : $(or_not_found bundle -v)"
echo "...Passenger Version: $(or_not_found passenger -v)"
答案 2 :(得分:0)
如果您使用bash> = 4.0,请在第一行echo
之前插入此行:
command_not_found_handle() { echo "not found"; return 127; }
然后在最后echo
行之后插入此字符以摆脱此功能:
unset command_not_found_handle
输出,例如:
...RVM Version : not found ...Node Version : v4.2.6 ...Ruby Version : ruby 2.3.1p112 (2016-04-26) [x86_64-linux-gnu] ...Bundler Version : not found ...Passenger Version: not found