linux - 检查 bash 中的命令是否输出了正确的动态值和字符串

标签 linux bash grep command output

我正在尝试制作一个 bash 脚本来检查特定命令是否已输出预期结果。输出应该是 N user(s) 已在输出文件中导出。

如果 N 是数字中的动态值,我应该如何检查它

我用这段代码来检查,但这只会检查特定的字符串:

./command.sh -e | grep 'string' &> /dev/null
    if [ $? == 0 ]; then
       echo "PASS" 
    fi

最佳答案

使用以下 grep 命令只会从输出中获取数字结果:N user(s):

grep -oP '^[0-9]+'

例子:

echo '1 user(s)' | grep -oP '^[0-9]+'

输出:

1

echo '100 user(s)' | grep -oP '^[0-9]+'

输出:

100

请注意,输出应该是 N user(s),您是否还有其他可能破坏此正则表达式的情况?

更新:

为了检查整个输出,你可以使用这个:

echo '1 user(s) has been exported in the output file' | grep -P '^[0-9]+\suser\(s\)\shas\sbeen\sexported\sin\sthe\soutput\sfile'

echo '1 user(s) has been exported in the output file' | grep -P '^[0-9]+\suser\(s\)\s(\w|\s)+'

echo '1 user(s) has been exported in the output file' | grep -P '^[0-9]+\s\w+\(\w\)(\s|\w)+'

输出:

1 user(s) has been exported in the output file

关于linux - 检查 bash 中的命令是否输出了正确的动态值和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44042502/

相关文章:

linux - 输出最后六个字符串

linux - grep 和 sed 文件名中有空格

linux - Erlang,process_flag trap_exit 从 CLI 杀死了我的 gen_server

linux - 如何在最小的 linux 安装上 "docker run"一个 shell session 并立即拆除容器?

linux - 如何在循环的 bash 脚本中引用 "next"命令行参数?

bash - 将两个文件的头部通过管道传输到一个文件

regex - 如何在两个明确定义的模式之间匹配最多 n 个自由字符的字符串?

linux - 管道与消息队列

linux - 在 Ubuntu 9.04 上为 SimpleScalar 安装 gcc

c++ - boost同步客户端错误