确保用户准确输入我想要的信息的正确方法是什么,或者以正确的期望回应声明?我有一个 bash 脚本,它有 4 个需要特定输入形式的变量,但我不知道如何检查它们的输入。
这些是我用来完成命令的变量:
read -p "Enter ID: " ID #SONGID can only be 10 digits long
read -p "Enter directory to search in e.g ab,cd,ef: " DIR #Directories are two letters and range from a-z
read -p "This abbreviation needs to match previous choice e.g ab, cd, ef: " FILE
read -p "Enter date of file e.g 20140503 or 201405*: " DATE
现在我编写脚本的方式无论如何都会继续。
SONGID="10"
if [ $(echo "SONGID" | grep -E "[0-10") ] &&
echo "Song ID good"
else
echo "ID needs to be 10 digits"
exit
fi
最佳答案
您可以使用类似于以下的模式。纯 Bash。您确信当您离开 while
循环时,数据已被相应的函数验证——所以如果出现问题,您将不得不责怪该函数,而不是程序的结构<支持>1.
#!/bin/bash
validate_ID() {
# Success if and only if $1 is a string of 10 digits
[[ $1 =~ ^[[:digit:]]{10}$ ]]
}
validate_dir() {
# Success if and only if $1 is a string of 2 letters in the range [a-z]
[[ $1 =~ ^[abcdefghijklmnopqrstuvwxyz]{2}$ ]]
# Hard-coded here for security, since depending on locales, other characters
# would pass, e.g., é. Try it: [[ é =~ [a-z] ]]; echo $?
}
validate_file() {
# I didn't understand the requirements... this always succeeds for now
return 0
}
validate_date() {
# Don't know how you want to validate this... this always succeeds for now
return 0
}
while :; do
IFS= read -rep "Enter ID: " songID
history -s -- "$songID"
validate_ID "$songID" && break
echo "Bad ID"
done
while :; do
IFS= read -rep "Enter directory to search in e.g ab,cd,ef: " dir #Directories are two letters and range from a-z
history -s -- "$dir"
validate_dir "$dir" && break
echo "Bad dir"
done
while :; do
IFS= read -rep "This abbreviation needs to match previous choice e.g ab, cd, ef: " file
history -s -- "$file"
validate_file "$file" && break
echo "Bad file"
done
while :; do
IFS= read -rep "Enter date of file e.g 20140503 or 201405*: " date
history -s -- "$date"
validate_date "$date" && break
echo "Bad date"
done
history
命令:每个命令都会将读取的值插入到历史记录中,以便用户可以使用向上箭头(尝试使用和不使用)检索以前的值——注意 -e
标志到 read
命令以使用 readline。 TAB 补全适用于文件名。
注意。目前有两个验证函数没有完成它们的工作;我不完全明白你想如何验证数据。
1其他一些 REPL 设计可能会失败,例如,
while read a; do
validate "$a" && break
echo "$a is invalid"
done
看起来不错,但如果读取有错误就会失败,例如,用户可以输入任意数据,按几次 Ctrl-D,你就会在变量 a
.
关于linux - If/else 有 4 个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23483511/