如何检查是否参数是合法的? [英] How to check if arguments are legit?
问题描述
我必须写一个bash脚本,将计算在一个文本文件中的所有命令。参数脚本是 -p
, -n NUM
和文件。这意味着这样的命令:
I have to write a bash script which will count all the commands in a text file. Arguments to a script are -p
, -n num
, and a file. This means that commands like:
script.sh -n 3 -p file.txt
script -p -n 3 file.txt
和类似的都是合法的。
不过,我必须回应一个错误是没有类似这样的命令: script.sh -n -k file.txt的
例如
However, I have to echo an error for any commands that are not similar to this: script.sh -n -k file.txt
for example.
下面是一个链接到我的code 。
我设法使它工作,但它是太长和冗余。有没有一种方法,我可以在很短的方式做到这一点?
I managed to make it work, but it is way too long and redundant. Is there a way I can do this in a short way?
推荐答案
我想提出另一个片段,它是简单了很多比你的阅读,因为它准确地描述了您在您的评论指定的唯一两个有效的情况:
I'd like to suggest another snippet that is a lot simpler to read than yours, because it exactly depicts the only two valid cases you specified in your comment:
如果我想呼我的脚本它看起来像这样: script.sh -n +数字-p file.txt的
。 file.txt的
必须是最后一个参数,但 -n
和 -p
可切换。
If I want to "call" my script it has to look like this:
script.sh -n +number -p file.txt
.file.txt
must be the last argument, however,-n
and-p
can be switched.
所以案件( $ 1,0
到 $ 4'/ code>)
So the cases are ($0
to $4
):
-
script.sh
-n
+号
-p
file.txt的
-
script.sh
-p
-n
+号
file.txt的
script.sh
-n
+number
-p
file.txt
script.sh
-p
-n
+number
file.txt
它仅使用如果
和Bash的逻辑运算符:
It uses only if
and Bash's logical operators:
#!/bin/bash
if ! { [[ "$1" = "-n" ]] && [[ "$2" =~ ^-[0-9]+$ ]] && [[ "$3" = "-p" ]] && [[ "$4" =~ ".txt"$ ]] ; } &&
! { [[ "$2" = "-n" ]] && [[ "$3" =~ ^-[0-9]+$ ]] && [[ "$1" = "-p" ]] && [[ "$4" =~ ".txt"$ ]] ; }
then
echo "Error" && exit 1
fi
注:
- 组(
{
,}
)语法需要一个;
在其列表的末尾。 - 您必须使用正则表达式来检查
*。txt的
- 您给需要的数量开始以
的数量正则表达式 -
,而在您的规格你说+
。
- The group (
{
,}
) syntax expects a;
at the end of its list. - You have to use a regex to check for
*.txt
- The number regex you gave will require the number to start with a
-
, while in your specification you say+
.
这篇关于如何检查是否参数是合法的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!