応答に「接続成功」という文字列が含まれるまでbashスクリプトでこのコマンドを繰り返すにはどうすればよいですか?

応答に「接続成功」という文字列が含まれるまでbashスクリプトでこのコマンドを繰り返すにはどうすればよいですか?

私はこれでどこにも行けません。

10回繰り返し、出力に「Connection成功した」文字列が含まれている場合は、中断されるbashスクリプトを作成したいと思います。

ret=$?thenと同じことを試しましたが、1であっても引き続きif [$ret -ne 0]elseステートメントが表示されます。ret

今、「接続成功」という単語を見つけようとしていますが、その構文の使い方がわかりません。

だから私は次のようなものが欲しい:

for i in {1..10}
do
  ret=bluetoothctl connect 26:EE:F1:58:92:AF | grep "connection successful"

  if [$ret -ne ""]; then
    break
  fi
done

しかし、明らかに正しい構文を使用すると、$ret=bluetoothctl connect 26:EE:F1:58:92:AF | grep "connection successful"

どんな助けでも大変感謝します。

ベストアンサー1

grep一部のテキストがパターンと一致するかどうかをテストする場合は、出力を保存する必要はほとんどありません。代わりにオプションをgrep使用して呼び出し-qて、終了状態に応じて対処してください。

#!/bin/sh

tries=10

while [ "$tries" -gt 0 ]; do
    if bluetoothctl connect '26:EE:F1:58:92:AF' | grep -q 'connection successful'
    then
        break
    fi

    tries=$(( tries - 1 ))
done

if [ "$tries" -eq 0 ]; then
    echo 'failed to connect' >&2
    exit 1
fi

失敗および成功時に正常な終了状態が返される場合、ループのステートメントはbluetoothctl不要で、次のように短縮できgrepます。if

if bluetoothctl connect '26:EE:F1:58:92:AF' >/dev/null
then
    break
fi

実際には、bluetoothctlループ条件を一部として含めることもできます(ここに示すように、forループからループの使用に切り替えると仮定します)。while

#!/bin/sh

tries=10

while [ "$tries" -gt 0 ] && ! bluetoothctl connect '26:EE:F1:58:92:AF'
do
    tries=$(( tries - 1 ))
done >/dev/null

if [ "$tries" -eq 0 ]; then
    echo 'failed to connect' >&2
    exit 1
fi

使用を検討してくださいhttps://www.shellcheck.netシェルスクリプトの構文を確認してください。問題のスクリプトについては、テストには次のスペースが必要であると指定されています[ ... ]

  if [$ret -ne ""]; then
  ^-- SC1009 (info): The mentioned syntax error was in this if expression.
     ^-- SC1035 (error): You need a space after the [ and before the ].
     ^-- SC1073 (error): Couldn't parse this test expression. Fix to allow more checks.
                  ^-- SC1020 (error): You need a space before the ].
                  ^-- SC1072 (error): Missing space before ]. Fix any mentioned problems and try again.

空でない文字列のテストは、または[ -n "$ret" ]を使用して実行されます[ "$ret" != "" ]-neこれは山水テスト。

また、パイプの出力をret。あなたが使う計画は

ret=$( bluetoothctl ... | grep ... )

おすすめ記事