0

I'm trying to get a script to echo a message when a number like -9 is entered.

The arguments have to be passed from the command line

This is what I have now.

#!/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
4

2 回答 2

2

(( ... ))不是test

$ (( -1 < 1 )) ; echo $?
0
$ (( -1 > 1 )) ; echo $?
1
于 2013-06-12T04:14:45.613 回答
0

您需要使用[[and ]],而不是((and ))。前者是测试,后者是允许!=但不允许的表达式评估-lt

最重要的是,您的第一条错误消息略有偏差,这听起来像是您输入了比您应该输入的参数更多的参数,即使您没有输入任何参数。最好将其表述为"Must enter exactly one argument".

而且,由于$#是数字,我更喜欢使用数字比较,-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
于 2013-06-12T04:15:23.823 回答