
たとえば、次のような複数のユーザー入力ステートメントがあります。
read -r -p "Do u want to include this step (y) or not (n) (y/N)"? answer
if [[ "$answer" =~ ^[Yy]$ ]]; then
...
fi
私はこれらのすべての質問に自動的に「はい」と答える方法を探しています。ユーザーがoptionsを使用してスクリプトを呼び出す非対話型セッションを想像してみてください--yes
。追加のstdin
入力は必要ありません。
今すぐ考えられる唯一の方法は、別の条件を追加することです。各if文。
どんなアイデアがありますか?
答え1
read
これらの質問のみを使用し、変数が常に呼び出される場合は、次のようにanswer
置き換えてくださいread
。
# parse options, set "$yes" to y if --yes is supplied
if [[ $yes = y ]]
then
read () {
answer=y
}
fi
答え2
使用できるそれは1)、スクリプトをまったく変更する必要はありません。
$ grep . test.sh
#!/bin/bash
read -rp 'What say you? ' answer
echo "Answer is: $answer"
read -rp 'And again? ' answer2
echo "Answer 2 is: $answer2"
$
$ yes | ./test.sh
Answer is: y
Answer 2 is: y
指定した注文を無期限に繰り返し、指定しない場合はデフォルトを繰り返しますy
。
答え3
自動モードを確認してユーザーに問い合わせるなど、全体的な決定ロジックを関数に入れます。その後、各ケースで基本レベルで呼び出します。want_act
以下はそれ自体が真/偽の値を返します。基本レベルでは文字列比較は必要ありません。条件が実行する操作は読者にとって明確です。
#!/bin/bash
[[ $1 = --yes ]] && yes_mode=1
want_act() {
[[ $yes_mode = 1 ]] && return 0
read -r -p "Include step '$1' (y/n)? " answer
[[ $answer = [Yy]* ]] && return 0
return 1
}
if want_act "frobnicate first farthing"; then
echo "frobnicating..."
fi