Bash - [:太多的论点

时间:2014-08-28 13:58:43

标签: bash

#!/bin/bash
# portcheck tool

usage()
{
    echo -e "\n USAGE: ./${0##*/} [host|ip] \n"
    exit
}

check_port()
{
    local host=${1}
    local port=${2}
    if [ nc -w 5 -z host port ] &&  [ nc -w 5 -z host port ]
    then
    echo -e "\a\n => Port ${port} at ${host} is open"
    else
    echo -e "\a\n => Port ${port} at ${host} is closed"
    fi
}

[[ $# -ne 2 ]] && usage

check_port ${1} ${2}

当我运行以下命令时:

bash portOpenBash.sh 127.0.0.1 434

我收到以下错误:

portOpenBash.sh: line 14: [: too many arguments

我尝试在宏表达式之间加上引号,但是我得到了同样的错误。

1 个答案:

答案 0 :(得分:1)

问题似乎出现在if条件中:

 if [ nc -w 5 -z host port ] &&  [ nc -w 5 -z host port ]

您可能希望检查两个命令的非空输出,如下所示:

if [ -n "$(nc -w 5 -z $host $port)" ] && [ -n "$(nc -w 5 -z $host $port)" ]

OR在BASH:

if [[ -n "$(nc -w 5 -z $host $port)" && -n "$(nc -w 5 -z $host $port)" ]]

修改

或者,如果您只想查看返回代码,请移除周围的[]

 if nc -w 5 -z $host $port && nc -w 5 -z $host $port