如何检查用户输入日期是否正确格式
我正在尝试在 shell 中结合命令最后编写一个 if 语句 if 语句应该检查最后一个命令的输出,并仅打印用户选择的月份的行。例如,用户输入是:三月一月
结果应该是:“三月良好格式” 并最后打印命令中以 Mar 作为月份的所有行。
对于一月,它应该显示:“一月格式错误”并且不打印任何其他内容。
这是到目前为止的代码:
echo "Enter the month name (acording to last command results format):"
read month month1
if [[ $month == [aA-zZ][aA-zZ][aA-zZ] ]]
then
echo "$month Good format"
else
echo "$month Bad format"
fi
它仅检查其中一项输入并仅打印一项输入。 我不知道如何检查一个 if 语句中的两个字符串并打印两个字符串的结果(如果一个失败而另一个正确)。
I am trying to write an if statement in shell combined with command last
The if statement should check the output of command last and print only the lines of which month user chose. For example user input is: Mar January
Result should be: "Mar Good format"
and print all the lines of the command last that have Mar as their month.
For January it should say: "January Bad format" and print nothing else.
This is the code so far:
echo "Enter the month name (acording to last command results format):"
read month month1
if [[ $month == [aA-zZ][aA-zZ][aA-zZ] ]]
then
echo "$month Good format"
else
echo "$month Bad format"
fi
It only checks for one of the inputs and prints only for one input.
I don't know how to check both of the strings in one if statement and print the results for both, if one fails and the other is correct.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@Nic3500 提供的解决方案的一种变体是分隔空字符串测试,然后使用
[[ ... ]]
测试传递给函数的月份的子字符串匹配,可以是:
[[ ... ]]
变量引用不是必需的,但会影响右侧正则表达式的计算方式。示例使用/输出
上面修改后的脚本将脚本的命令行参数传递给要检查的函数,例如
@Nic3500 提出的数组作为查找是一个非常好的方法。不过,当与
[[ ... ]]
一起使用时,一个简单的空格分隔的允许名称字符串也可以工作。A variation of the solution offered by @Nic3500 that separates the empty string test and then uses the
[[ ... ]]
test for a substring match of the months passed to the function could be:When using
[[ ... ]]
variable quoting isn't necessary, but does influence how the right side regex is evaluated.Example Use/Output
The modified script above passes the command-line arguments of the script to the function to be checked, e.g.
The array as a lookup proposed by @Nic3500 is a very good approach. Though when used with
[[ ... ]]
a simple space separated string of allowable names will work as well.一种方法是:
valid_values
是一组有效值。检查月份值是否为三个字符是不够的,因为abc
不是有效的月份值。if
检查函数接收到的值是否位于数组中的某个位置。if
还会验证月份值是否为空,以防万一您的用户仅键入 1 个值(或根本没有值)。One way you could do that is:
valid_values
is an array of good values. Checking that the month value is three characters is not enough, sinceabc
is not a valid month value.if
checks if the value received by the function is somewhere in the array.if
also verifies if the month value is empty, just in case your user types only 1 value (or no value at all).