Oğu*_*ğuz 5 shell-script function exit-status
我想通过返回值来查询函数。我的代码如下;
check(){
file=/root/Turkiye.txt
local funkx=$1
while read line; do
if [ "$line" == "$funkx" ]
then
true
break
else
false
fi
done < $file
}
printf "Please enter the value : "
read keyboard
if check $keyboard;
then
echo "yes";
else
echo "no";
fi
Run Code Online (Sandbox Code Playgroud)
它不起作用,我做错了什么?
true和false是分别以成功和失败退出代码退出的命令。它们不会让您的函数返回这些值,为此请使用return命令以及对应于成功 (0) 或失败(0 以外的任何值)的整数值。另外,我很确定您不想为不匹配的第一行返回失败,只要没有匹配的行:
check(){
file=/root/Turkiye.txt
local funkx=$1
while read line; do
if [ "$line" == "$funkx" ]
then
return 0 # 0 = success ("true"); break is not needed because return exits the function
fi
done < $file
# If a line matched, it won't get here (it will have returned out of the middle
# of the loop). Therefore, if it gets here, there must not have been a match.
return 1 # 1 = failure ("false")
}
Run Code Online (Sandbox Code Playgroud)
但是有一种更简单的方法可以做到这一点。使用grep——它的工作是搜索匹配行的文件。您想要grep -Fxq---F意味着搜索固定字符串(不是正则表达式模式),-x意味着需要匹配整行,而不仅仅是其中的一部分,并且-q意味着不要打扰打印结果,如果找到匹配,则以成功状态退出, 否则失败。而且您甚至不需要显式return命令,因为该函数将隐式返回其中最后一个命令的状态:
check(){
file=/root/Turkiye.txt
local funkx=$1
grep -Fxq "$funkx" "$file"
}
Run Code Online (Sandbox Code Playgroud)
或者更简单:
check(){
grep -Fxq "$1" /root/Turkiye.txt
}
Run Code Online (Sandbox Code Playgroud)