name01=$(echo "Data 01")
name02=$(echo "Data 02")
echo "Please select data : "
PS3="Answer : "
optionname=(
"$name01"
"$name02"
"$name99")
select opt1 in "${optionname[@]}"
do
case $opt1 in
$name01) echo "$name01" ; break ;;
$name02) echo "$name02" ; break ;;
$name99) echo "Please enter the data : " ; read "name99" ; break ;;
*) echo invalid option;;
esac
done
这是我当前脚本的一部分,目前只有12个数据,但数据的数量和名称会随着时间的推移而改变,所以我需要数据/变量(name01,name02,name03,...)从单独的文本文件中的列表导入。假设文件里面的内容如下:
aa bb
aaaa ccc
ab cdd
需要建议,
提前致谢
答案 0 :(得分:0)
如果您只想根据文件中的选项列表验证用户输入,那么您只需使用grep
:
给出options.txt
中的选项列表。
banana
apple
pear
脚本(option.bash
):
#!/bin/bash
read -p 'Please enter your favourite fruit: ' fruit_input
if grep -q -o -x -- "$fruit_input" options.txt; then
echo "Your favourite fruit is: $fruit_input"
else
echo "The only fruits you're allowed to choose are:"
cat options.txt
fi
您可以使用grep验证用户是否输入了允许的选项:
./option.bash
Please enter your favourite fruit: apple
Your favourite fruit is: apple
./option.bash
Please enter your favourite fruit: cheese
The only fruits you're allowed to choose are:
banana
apple
pear
答案 1 :(得分:0)
以下是我的脚本的更新,列表位于/tmp/name_list
touch /tmp/number_list
touch /tmp/number_name_list
amount=$(cat /tmp/name_list | wc -l)
a=0
while [[ $a -lt $amount ]]; do
let a=$a+1
echo $a >> /tmp/number_list
name=$(sed -n "${a}p" /tmp/name_list)
echo "$a $name">> /tmp/number_name_list
done
cat /tmp/number_name_list
read -p "Please enter the number or enter new name : " input
if
grep -q -o -x -- "$input" /tmp/number_list
then
folder=$(sed -n "${input}p" /tmp/name_list)
echo "its $folder"
mkdir /tmp/"$folder"
else
echo "its $input"
mkdir /tmp/"$input"
fi
感谢@Robert Seaman提醒我使用if then else
代替case