Bash loop control while if else with a return

℡╲_俬逩灬. 提交于 2020-01-06 14:42:46

问题


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.

is_file_contains_VAR(){
    VARFILENAME=$1

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

回答1:


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

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

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

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

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


来源:https://stackoverflow.com/questions/21976244/bash-loop-control-while-if-else-with-a-return

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!