组合多个 if b

组合多个 if b

我该如何简化以下代码 if 语句?谢谢

function git_dirty {
    text=$(git status)
    changed_text="Changes to be committed"
    changes_not_staged="Changes not staged for commit"
    untracked_files="Untracked files"

    dirty=false

    if [[ ${text} = *"$changed_text"* ]];then
        dirty=true
    fi

    if [[ ${text} = *"$changes_not_staged"* ]];then
        dirty=true
    fi

    if [[ ${text} = *"$untracked_files"* ]];then
        dirty=true
    fi

    echo $dirty
}

答案1

好吧,这是一个多条件版本的 if,因为每个语句都有相同的有效负载。

if [[ ${text} = *"$changed_text"* -o  ${text} = *"$changes_not_staged"* -o ${text} = *"$untracked_files"*]];then
            dirty=true
        fi

-oif 中的条件之间指定“或”关系,而-a指定“与”关系。

答案2

在 Mac 上,它抱怨,因此我去了 shellcheck.net,它抱怨-o但没有说原因,只是说使用,||所以我这样做了:

if [[ ${text} = *"$changed_text"* ||  ${text} = *"$changes_not_staged"* || ${text} = *"$untracked_files"* ]]; then
        dirty=true
    fi

我得到了

$ src
-bash: /Users/cchilders/.bash_profile: line 384: syntax error in conditional expression
-bash: /Users/cchilders/.bash_profile: line 384: syntax error near `-o'
-bash: /Users/cchilders/.bash_profile: line 384: `    if [[ ${text} = *"$changed_text"* -o  ${text} = *"$changes_not_staged"* -o ${text} = *"$untracked_files"* ]]; then'

相关内容