加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 检查命令错误是否包含子字符串

发布时间:2020-12-15 18:58:07 所属栏目:安全 来源:网络整理
导读:我有很多bash命令.其中一些因各种原因而失败. 我想检查一些错误是否包含子字符串. 这是一个例子: #!/bin/bashif [[ $(cp nosuchfile /foobar) =~ "No such file" ]]; then echo "File does not exist. Please check your files and try again."else echo "N
我有很多bash命令.其中一些因各种原因而失败.
我想检查一些错误是否包含子字符串.

这是一个例子:

#!/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

当我运行它时,错误被打印到屏幕上,我得到“不匹配”:

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

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

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

如何正确匹配错误消息?

附:我找到了一些解决方案,您对此有何看法?

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(破折号比bash快一点).

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读