Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 当传递的参数小于1时出错,我在做什么?_Linux_Bash_Shell_Scripting - Fatal编程技术网

Linux 当传递的参数小于1时出错,我在做什么?

Linux 当传递的参数小于1时出错,我在做什么?,linux,bash,shell,scripting,Linux,Bash,Shell,Scripting,我正在尝试获取一个脚本,以便在输入像-9这样的数字时回显消息 必须从命令行传递参数 这就是我现在拥有的 #!/bin/bash #Assign1part1 if (( $# != 1 )); then echo "Error: Must only enter one argument" >&2 exit 1 fi if (( $1 -lt 1 )); then echo "Error: Argument must be a positive intege

我正在尝试获取一个脚本,以便在输入像-9这样的数字时回显消息

必须从命令行传递参数

这就是我现在拥有的

#!/bin/bash
#Assign1part1

if (( $# != 1 )); then
    echo "Error: Must only enter one argument" >&2
    exit 1
fi

if (( $1 -lt 1 )); then
    echo "Error: Argument must be a positive integer" >&2
    exit 1
fi

seq -s, $1 -1 1
(…)
不是
测试

$ (( -1 < 1 )) ; echo $?
0
$ (( -1 > 1 )) ; echo $?
1
$(-1<1));回声$?
0
$ (( -1 > 1 )) ; 回声$?
1.

您需要使用
[[
]
,而不是
)。前者是测试,后者是表达式求值,它允许
=但不是
-lt

最重要的是,您的第一条错误消息稍微有点不正确,这使得您输入的参数似乎比您应该输入的要多,即使在没有输入参数的情况下也是如此。它的措辞最好是像
“必须只输入一个参数”

而且,由于
$#
是数字的,我更喜欢使用数字比较,
-ne
而不是
=在这种特殊情况下

换言之:

#!/bin/bash
#Assign1part1

if [[ $# -ne 1 ]]; then
    echo "Error: Must enter exactly one argument" >&2
    exit 1
fi

if [[ $1 -lt 1 ]]; then
    echo "Error: Argument must be a positive integer" >&2
    exit 1
fi

seq -s, $1 -1 1
使用特定的测试数据运行该测试将给出:

pax> testprog 5
5,4,3,2,1

pax> testprog 9
9,8,7,6,5,4,3,2,1

pax> testprog
Error: Must enter exactly one argument

pax> testprog 1 2
Error: Must enter exactly one argument

pax> testprog -7
Error: Argument must be a positive integer

bash喜欢
。但是
不喜欢
-lt
.hmm[[对我来说似乎什么都没有。而且,我向你致敬,好先生。在这个网站上有没有一种与人聊天或给人小费的方法?你们这些家伙应该为你们的甜食得到一些mah现金skills@Looking2learned:不,只需投票选出有用的答案并接受最佳答案。这是这里使用的货币。