问题
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