Bashスクリプト関数はTrue-Falseを返します。

Bashスクリプト関数はTrue-Falseを返します。

値を返して関数を照会したいです。私のコードは次のとおりです。

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

動作しません。私が何を間違っているのでしょうか?

ベストアンサー1

truefalseそれぞれ成功と失敗の終了コードで終了するコマンドです。関数がこれらの値を返すことはできません。これを行うには、コマンドreturnと成功(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")
}

しかし、これを行うより簡単な方法があります。使用grep- そのアクションは、ファイル内の一致する行を検索することです。grep -Fxq--F正規表現パターンではなく固定文字列検索を意味し、行-xの一部ではなく行全体と一致する必要があることを意味し、-q一致するものが見つかった場合は成功した状態で結果を印刷する必要がないことを意味します。終了し、そうでなければ失敗します。return関数は暗黙的に最後のコマンドのステータスを返すため、明示的なコマンドも必要ありません。

check(){
    file=/root/Turkiye.txt
    local funkx=$1
    grep -Fxq "$funkx" "$file"
}

それとももっと簡単です:

check(){
    grep -Fxq "$1" /root/Turkiye.txt
}

おすすめ記事