Bash 脚本函数返回真假

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)

它不起作用,我做错了什么?

Gor*_*son 7

truefalse是分别以成功和失败退出代码退出的命令。它们不会让您的函数返回这些值,为此请使用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)

  • @D.BenKnoble 你是对的,但原始脚本所做的事情远没有那么明显。事实上,您可以删除原始脚本中的 `true` 和 `false` 命令(或反转它们)并且不会改变结果。这是因为如果一行匹配,它执行`true`,*然后`break`*,所以返回状态来自`break`命令(将为0)。类似地,如果没有找到匹配,最后执行的命令是循环测试,`read line`(将为 1)。所以它实际上得到了正确的结果,但不是出于合理的原因。 (2认同)