Bash 循环控制 while if else 带返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21976244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:40:04  来源:igfitidea点击:

Bash loop control while if else with a return

bashwhile-loop

提问by MAXGEN

I need to return a true or false if I find a value within a file. I parse the file and if the value is located once which is enough, I want to break and return a true else return false. On top of it I need to pass the file into this check function. I'm trying to only use bash.

如果我在文件中找到一个值,我需要返回 true 或 false。我解析文件,如果该值定位一次就足够了,我想中断并返回真否则返回假。最重要的是,我需要将文件传递给这个检查函数。我试图只使用 bash。

is_file_contains_VAR(){
    VARFILENAME=

    while read LINE
    do
        if echo "$LINE" | grep -q "$VAR"; then
            break
            return 0   
        else
            return 1
        fi
    done < $VARFILENAME
}

回答by ruakh

grep -qalready does what you want: it will abort as soon as it finds the string in question. So you can just write:

grep -q已经做了你想要的:它会在找到有问题的字符串后立即中止。所以你可以写:

function is_file_contains_VAR () {
    grep -q -e "$VAR" ""
}

(Note: the -eis in case "$VAR"starts with a hyphen.)

(注意:-e以防万一"$VAR"以连字符开头。)

But for educational purposes . . . to write this as a loop, what you would want is to return 0as soon as there's a match, and only return 1at the very end, if you never find a match:

但出于教育目的。. . 要将其编写为循环,您想要的是return 0一旦有匹配项,并且仅return 1在最后,如果您从未找到匹配项:

function is_file_contains_VAR () {
    local VARFILENAME=""
    local LINE
    while IFS= read -r LINE ; do
        if grep -q -e "$VAR" <<< "$LINE" ; then
             return 0
        fi
    done < "$VARFILENAME"
    return 1
}