问题描述
我有一组 100 个问题。我的要求是当用户输入“是”时,应该出现问题 1。如果没有,直接跳到第2题。这样应该一直持续到100题。任何线索将不胜感激。
这是我尝试过的,但失败了。
#!/bin/bash
echo "Execute question1 "
select result in Yes No
do
echo "How to see apache config file"
exit
done
echo "execute question2"
select result in Yes No Cancel
do
echo "Command for listing processes"
exit
done
提前致谢
解决方法
这是一种使用数组执行此操作的方法。
#!/bin/bash
questions=(
"How to see apache config file"
"Command for listing processes"
"My hovercraft is full of eels"
)
for((q=0; q<${#questions[@]}; q++)); do
echo "Execute question $q?"
select result in Yes No; do
case $result in
Yes)
echo "${questions[q]}";;
esac
break
done
done
不过,为此使用 select
似乎相当笨拙。也许只是将其替换为
read -p "Execute question $q? " -r result
case $result in
[Yy]*) echo "${questions[q]}";;
esac
只有一个问题列表似乎仍然很奇怪。使用 Bash 5+,您可以拥有一个关联数组,或者您可以拥有一个具有相同索引和问题答案的并行数组。但是将每个问题和答案对放在源中会更有意义。也许循环问题和答案并将每个其他问题和答案分配给一个 answers
数组,并且仅在您阅读一对时才增加索引?
pairs=(
"How to see Apache config file"
"cat /etc/httpd.conf"
"Command for listing processes"
"ps"
"My hovercraft is full of what?"
"eels"
)
questions=()
answers=()
for((i=0; i<=${#pairs[@]}/2; ++i)); do
questions+=("${pairs[i*2]}")
answers+=("${pairs[1+i*2]}")
done
这最终会得到所有东西的两个副本,所以如果你真的被内存束缚住了,也许可以重构为一个 for
循环遍历字符串并去掉 pairs
数组,它只是有用的初始化期间。
使用一系列问题并循环遍历它,如下所示:
#!/bin/bash
n=1
questions=(
'How to see apache config file'
'Command for listing processes'
)
check_user_input(){
read -p "y/n " input
case $input in
[Yy]*) return 0;;
[Nn]*) return 1;;
*) check_user_input;;
esac
}
for question in "${questions[@]}"; {
echo "Execute question $n"
check_user_input && echo "$question"
((n++))
}
,
这是一个直接示例。玩它。
#!/bin/bash
echo "Type 'y' for yes,'n' to skip or 'q' to quit and press Enter!"
for((i=1; i < 101; ++i)); do
echo 'Execute question '$i
while read user_input; do
if [[ "$user_input" = 'q' ]]; then
break 2
elif [[ "$user_input" = 'n' ]]; then
break
elif [[ $i -eq 1 ]]; then
echo 'How to see apache config file?'
break 2 # Change from "break 2" to "break" for the next question.
elif [[ $i -eq 2 ]]; then
echo 'Command for listing processes.'
break 2 # Change from "break 2" to "break" for the next question.
else
echo "Wrong input: $user_input"
echo "Type 'y' for yes,'n' to skip or 'q' to quit and press Enter!"
fi
done
done
echo 'Finished'