Bash的闭环控制而如果别人有回报 [英] Bash loop control while if else with a return
问题描述
我需要的,如果我找到一个文件中的值返回一个true或false。我分析文件,如果值位于这一次就够了,我想打破,返回真,否则返回假。在它的上面我需要将文件传递到这个检查功能。我想只使用bash。
is_file_contains_VAR(){
VARFILENAME = $ 1 而读线
做
如果回声$ LINE| grep的-q$ VAR;然后
打破
返回0
其他
返回1
科幻
完成< $ VARFILENAME
}
的grep -q
已经做你想要什么:它会尽快找到的字符串中止题。所以你可以这样写:
函数is_file_contains_VAR(){
grep的-q -e$ VAR$ 1
}
(注: -e
是万一$ VAR
开始于一个连字符。)
但是教育目的。 。 。写这作为一个循环,你会想是返回0
只要有一个匹配,只有收益1
在最后,如果你从来没有找到匹配的:
函数is_file_contains_VAR(){
当地VARFILENAME =$ 1
焦线
而IFS =读-r线;做
如果grep的-q -e$ VAR<<< $ LINE;然后
返回0
科幻
完成< $ VARFILENAME
返回1
}
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
}
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
}
这篇关于Bash的闭环控制而如果别人有回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!