
現在、3番目のシェルスクリプトを作成していますが、問題が発生しました。これはこれまで私のスクリプトです。
#!/bin/bash
echo "choose one of the following options : \
1) display all current users \
2) list all files \
3) show calendar \
4) exit script"
while read
do
case in
1) who;;
2) ls -a;;
3) cal;;
4) exit;;
esac
done
スクリプトを実行しようとすると、次のように表示されます。
line2 : unexpected EOF while looking for matching '"'
line14 : syntax error: unexpected end of file.
私は何が間違っていましたか?
答え1
忘れないでくださいselect
:
choices=(
"display all current users"
"list all files"
"show calendar"
"exit script"
)
PS3="your choice: "
select choice in "${choices[@]}"; do
case $choice in
"${choices[0]}") who;;
"${choices[1]}") ls -a;;
"${choices[2]}") cal;;
"${choices[3]}") break;;
esac
done
答え2
問題は、あなたのcase
ステートメントに与えられた、つまり評価する必要がある変数が欠落していることです。したがって、次のようなことをしたいかもしれません。
#!/bin/bash
cat <<EOD
choose one of the following options:
1) display all current users
2) list all files
3) show calendar
4) exit script
EOD
while true; do
printf "your choice: "
read
case $REPLY in
1) who;;
2) ls -a;;
3) cal;;
4) exit;;
esac
done
これには、case
変数名が指定されていない場合に入力されるデフォルト変数が使用されます(詳細を参照$REPLY
)。read
help read
また、変更に注意してください。printf
ラウンドごとにプロンプトを表示し(新しい行を追加しない)、cat
複数行に指示を印刷して、改行なしで読みやすくしました。
答え3
まず、単一のケースを試してみましょう。これを使用して、以下のようにread -p
ユーザー入力を変数として読み込み、Case文を読みます。opt
#!/bin/bash
read -p "choose one of the following options : \
1) display all current users \
2) list all files \
3) show calendar \
4) exit script" opt
case $opt in
1) who;;
2) ls -a;;
3) cal;;
4) exit;;
esac
上記のスクリプトはうまくいきます。これで、ユーザーがオプション4を押すまでユーザー入力を読み取れるようにループに入れる必要があると思います。
だから私たちはwhile
以下のループを使ってこれを行うことができます。opt
変数の初期値を0に設定しました。次に、変数値が0のwhile
間opt
ループを繰り返します。これがopt
ステートメントの最後で変数をゼロにリセットする理由ですcase
。
#!/bin/bash
opt=0;
while [ "$opt" == 0 ]
do
read -p "choose one of the following options : \
1) display all current users \
2) list all files \
3) show calendar \
4) exit script" opt
case $opt in
1) who;;
2) ls -a;;
3) cal;;
4) exit;;
esac
opt=0
done
答え4
個人的には、コードの先頭に「while」を入れます。その後、それに従うと、:
好きなだけ繰り返すことができます。それが私が書いた方法です。
while :
do
echo "choose one of the following options : \
1) display all current users \
2) list all files \
3) show calendar \
4) exit script"
read string
case $string in
1)
who
;;
その後、質問を続け、最後に仕上げます。
esac
done