ループで呼び出された関数から「続き」を返します。

ループで呼び出された関数から「続き」を返します。

私は現在徐々に制御不能状態になっていくスクリプトをリファクタリングしています。繰り返しを機能に分解しようとしています。しかし、ループで呼び出される反復テストがあり、このテストがcontinue

シェルチェック

SC2104: In functions, use `return` instead of `continue`.

Shellcheck Wikiにはこれをしないように言われています。しかし、方法がありますか?

以下は例です。

#!/bin/sh

AFunction () {
    if [[ "${RED}" -lt 3 ]]; then
        echo "cont"
        continue
    else
        echo "nope"
    fi
}

for i in 1 2 3 4 5
do
    RED=${i}
    AFunction
    echo ${i}
done

出力は次のとおりです。

cont
1
cont
2
nope
3
nope
4
nope
5

しかし、私は願っています

cont
cont
nope
3
nope
4
nope
5

今まで答えてくれた皆さんに感謝します。私はかなり近づいていますが、今では付随的な問題があります。そんな風にしても大丈夫でしょうか?

@sudodusの答えと@alecxsのヒントを組み合わせて使用​​する場合。関数が終わったら、常に0を「返す」必要がありますか?今は良い習慣のように見えますが、明示的に実行しないと意味がありますか?

#!/bin/sh

AFunction () {
    ##Script doing loads of other stuff
    if [[ "${RED}" -lt 3 ]]; then
        echo "cont"
        ## This only happening because something has gone wrong
        return 1
    else
        echo "nope"
    fi
    ##Script doing loads of more stuff
}

for i in 1 2 3 4 5
do
    RED=${i}
    AFunction || continue
    echo ${i}
done

ベストアンサー1

以下のパラメータで「return」を使用できます。

#!/bin/bash

AFunction () {
    if [[ "${RED}" -lt 3 ]]; then
        echo "cont"
        return 1
    else
        echo "nope"
        return 0
    fi
}

for i in 1 2 3 4 5
do
    RED=${i}
    if AFunction
    then
    echo ${i}
    fi
done

おすすめ記事