我想我的Bash脚本打印一个错误消息,如果所需的参数计数没有满足。

我尝试了以下代码:

#!/bin/bash
echo Script name: $0
echo $# arguments 
if [$# -ne 1]; 
    then echo "illegal number of parameters"
fi

由于一些未知的原因,我得到了以下错误:

test: line 4: [2: command not found

我做错了什么?


当前回答

你应该在测试条件之间添加空格:

if [ $# -ne 1 ]; 
    then echo "illegal number of parameters"
fi

我希望这能有所帮助。

其他回答

这里有一个简单的一行程序来检查是否只给出了一个参数,否则退出脚本:

[ "$#" -ne 1 ] && echo "USAGE $0 <PARAMETER>" && exit

这里有很多有用的信息,但我想添加一个我认为有用的简单片段。

它与上面的一些有什么不同?

打印使用到标准错误,这比打印到标准输出更合适 返回另一个答案中提到的退出代码 不使它成为一个班轮…

_usage(){
    _echoerr "Usage: $0 <args>"
}

_echoerr(){
    echo "$*" >&2
}

if [ "$#" -eq 0 ]; then # NOTE: May need to customize this conditional
    _usage
    exit 2
fi
main "$@"

如果你在处理数字,使用算术表达式可能是个好主意。

if (( $# != 1 )); then
    >&2 echo "Illegal number of parameters"
fi

>&2用于将错误消息写入stderr。

On[]: !=, =, ==…是字符串比较操作符,-eq, -gt…都是算术二进制。

我会用:

if [ "$#" != "1" ]; then

Or:

if [ $# -eq 1 ]; then

如果你只对缺少特定参数的情况感兴趣,参数替换是很好的选择:

#!/bin/bash
# usage-message.sh

: ${1?"Usage: $0 ARGUMENT"}
#  Script exits here if command-line parameter absent,
#+ with following error message.
#    usage-message.sh: 1: Usage: usage-message.sh ARGUMENT