我正在运行 HP-UX 11.23,并且有一个读取两个输入的 bash 脚本。
两个输入的长度都必须正好是 6 位数字。
读取输入的最佳方式是什么?如果不是 6 个数字,则要求用户重试?
echo "Enter the 6 digit missing file numbers"
echo "You don't need to put USSR or .txt.got"
echo
echo "If you just have one file, enter the same number twice"
echo
echo "e.g 230123"
echo " 230130"
echo
echo "Enter the first file name"
read file1
while [ -z "$file1" ]; do
echo "The first file name is incorrect"
echo "Please enter 6 digit number again"
read file1
done
echo
echo "Enter second file name"
read file2
while [ -z "$file2" ]; do
echo "The last file name is incorrect"
echo "Please enter 6 digit number again"
read file2
done
if [ $file1 -le $file2 ]
then
echo "Sequence numbers look OK"
fi
答案1
valid() {
local d='[0123456789]'
case $1 in
($d$d$d$d$d$d) true;;
(*) false;;
esac
}
# or:
valid() {
# note that it clobbers $BASH_REMATCH even if you declare
# it locally to the function.
local re='^[0123456789]{6}$'
[[ $1 =~ $re ]]
}
until
IFS= read -rp 'First file: ' file1 || exit
valid "$file1"
do
echo >&2 Invalid, try again.
done
不要使用[0-9]
in 代替,[0123456789]
除非您同意它也可以匹配诸如٠١٢٣٤٥٦٧٨۰۱۲۳۴۵۶۷۸߀߁߂߃߄߅߆߇߈०१२३४५६७८০১২৩৪৫৬৭৮੦੧੨੩੪੫੬੭੮૦૧૨૩૪૫૬૭૮୦୧୨୩୪୫୬୭୮௦௧௨௩௪௫௬௭௮౦౧౨౩౪౫౬౭౮౸౹౺౻౼౽౾೦೧೨೩೪೫೬೭೮൦൧൨൩൪൫൬൭൮෦෧෨෩෪෫෬෭෮๐๑๒๓๔๕๖๗๘໐໑໒໓໔໕໖໗໘༠༡༢༣༤༥༦༧༨༪༫༬༭༮༯༰༱༳၀၁၂၃၄၅၆၇၈႐႑႒႓႔႕႖႗႘፩፪፫፬፭፮፯፰០១២៣៤៥៦៧៨៰៱៲៳៴៵៶៷៸᠐᠑᠒᠓᠔᠕᠖᠗᠘᥆᥇᥈᥉᥊᥋᥌᥍᥎᧐᧑᧒᧓᧔᧕᧖᧗᧘᧚᪀᪁᪂᪃᪄᪅᪆᪇᪈᪐᪑᪒᪓᪔᪕᪖᪗᪘᭐᭑᭒᭓᭔᭕᭖᭗᭘᮰᮱᮲᮳᮴᮵᮶᮷᮸᱀᱁᱂᱃᱄᱅᱆᱇᱈᱐᱑᱒᱓᱔᱕᱖᱗᱘⁰⁴⁵⁶⁷⁸₀₁₂₃₄₅₆₇₈⅐⅑⅒⅓⅔⅕⅖⅗⅘⅙⅚⅛⅜⅝⅞⅟ↅ↉①②③④⑤⑥⑦⑧⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳⑴⑵⑶⑷⑸⑹⑺⑻⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇⒈⒉⒊⒋⒌⒍⒎⒏⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛⓪⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴⓵⓶⓷⓸⓹⓺⓻⓼⓾⓿❶❷❸❹❺❻❼❽❿➀➁➂➃➄➅➆➇➉➊➋➌➍➎➏➐➑➓〇〡〢〣〤〥〦〧〨㉈㉉㉊㉋㉌㉍㉎㉏㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿㋀㋁㋂㋃㋄㋅㋆㋇㋉㋊㋋㍘㍙㍚㍛㍜㍝㍞㍟㍠㍢㍣㍤㍥㍦㍧㍨㍩㍪㍫㍬㍭㍮㍯㍰㏠㏡㏢㏣㏤㏥㏦㏧㏩㏪㏫㏬㏭㏮㏯㏰㏱㏲㏳㏴㏵㏶㏷㏸㏹㏺㏻㏼㏽㏾꘠꘡꘢꘣꘤꘥꘦꘧꘨꣐꣑꣒꣓꣔꣕꣖꣗꣘꤀꤁꤂꤃꤄꤅꤆꤇꤈꧐꧑꧒꧓꧔꧕꧖꧗꧘꧰꧱꧲꧳꧴꧵꧶꧷꧸꩐꩑꩒꩓꩔꩕꩖꩗꩘꯰꯱꯲꯳꯴꯵꯶꯷꯸012345678