首页 > 解决方案 > 如何查看一个命令的输出是否在另一个命令的输出中?

问题描述

我有两个命令。第一个,当存储在脚本变量中时,会给出如下输出:

one two three four five

第二个也给出了一个列表,但是第一个命令中的某些项目可能会丢失:

one three five

如果项目在第一个命令中而不是第二个命令中,我希望我的脚本执行某些操作。所有项目都没有空格(它们往往是kabab-format)。我怎样才能在 Bash 中做到这一点?

标签: bashcomm

解决方案


关于我的评论[1],我会像下面这样解决这个问题:

#!/bin/bash

res1=(one two three four five)
res2=(one three five)

for value in "${res1[@]}"; do
    if [[ ! "${res2[*]}" =~ "${value}" ]]; then

        # Do action
        echo "'$value' does not exist in res2"

        # Possibly stop for loop
        break
    fi
done

使用break,这将显示:

'two' does not exist in res2

没有break,它将显示:

'two' does not exist in res2
'four' does not exist in res2

推荐阅读