检查命令错误是否包含子字符串 [英] Check if command error contains a substring

查看:72
本文介绍了检查命令错误是否包含子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多bash命令,其中一些由于不同的原因而失败. 我想检查我的某些错误是否包含子字符串.

I have a lot of bash commands.Some of them fail for different reasons. I want to check if some of my errors contain a substring.

这是一个例子:

#!/bin/bash

if [[ $(cp nosuchfile /foobar) =~ "No such file" ]]; then
    echo "File does not exist. Please check your files and try again."
else
    echo "No match"
fi

当我运行它时,错误会显示在屏幕上,并且显示"No match":

When I run it, the error is printed to screen and I get "No match":

$ ./myscript
cp: cannot stat 'nosuchfile': No such file or directory
No match

相反,我希望捕获错误并使其符合条件:

Instead, I wanted the error to be captured and match my condition:

$ ./myscript
File does not exist. Please check your files and try again.

如何与错误消息正确匹配?

How do I correctly match against the error message?

P.S.我找到了一些解决方案,您对此有何看法?

P.S. I've found some solution, what do you think about this?

out=`cp file1 file2 2>&1`
if [[ $out =~ "No such file" ]]; then
    echo "File does not exist. Please check your files and try again."
elif [[ $out =~ "omitting directory" ]]; then
    echo "You have specified a directory instead of a file"
fi

推荐答案

我会这样做

# Make sure we always get error messages in the same language
# regardless of what the user has specified.
export LC_ALL=C

case $(cp file1 file2 2>&1) in 
    #or use backticks; double quoting the case argument is not necessary
    #but you can do it if you wish
    #(it won't get split or glob-expanded in either case)
    *"No such file"*)
        echo >&2 "File does not exist. Please check your files and try again." 
        ;;
    *"omitting directory"*)
        echo >&2 "You have specified a directory instead of a file"
        ;;
esac

这也可以与任何POSIX shell一起使用,如果您决定执行以下操作,它可能会派上用场 将您的bash脚本转换为POSIX shell(dashbash快很多).

This'll work with any POSIX shell too, which might come in handy if you ever decide to convert your bash scripts to POSIX shell (dash is quite a bit faster than bash).

您需要第一个2>&1重定向,因为可执行文件通常会将信息输出给stderr,这些信息主要不用于进一步的计算机处理. 您应该>&2重定向与echo一起使用,因为您在那里输入的内容符合该类别.

You need the first 2>&1 redirection because executables normally output information not primarily meant for further machine processing to stderr. You should use the >&2 redirections with the echos because what you're ouputting there fits into that category.

这篇关于检查命令错误是否包含子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆