在Ksh中合并多个if语句

3
我该如何将以下if语句合并为一行?
if [ $# -eq 4 ]
then
        if [ "$4" = "PREV" ]
        then
                print "yes"
        fi
fi
if [ $# -eq 3 ]
then
        if [ "$3" = "PREV" ]
        then
                print "yes"
        fi
fi

我正在使用ksh。为什么会出现错误?
if [ [ $# -eq 4 ] && [ "$4" = "PREV" ] ]
        then
                print "yes"
        fi

错误:

0403-012 测试命令参数无效。

3个回答

3

'['不是sh中的分组标记。您可以这样做:

if [ expr ] && [ expr ]; then ...

或者

if cmd && cmd; then ...

或者

if { cmd && cmd; }; then ...

您也可以使用括号,但语义略有不同,因为测试将在子shell中运行。

if ( cmd && cmd; ); then ...

此外,请注意,“if cmd1; then cmd2; fi”与“cmd1 && cmd2”完全相同,因此您可以编写:

test $# = 4 && test $4 = PREV && echo yes

但如果您的意图是检查最后一个参数是否为字符串PREV,则可以考虑:

eval test \$$# = PREV && echo yes

1
请注意,第一个示例仅是第二个示例的特殊情况,其中命令为“ [”。 - William Pursell

3

试试这个:

if [[ $# -eq 4 && "$4" == "PREV" ]]
then
    print "yes"
fi

您也可以尝试像这样将它们全部放在一起:

if [[ $# -eq 4 && "$4" == "PREV"  || $# -eq 3 && "$3" == "PREV" ]]
then
    print "yes"
fi

你只想检查最后一个参数是否为“PREV”吗?如果是,你也可以这样做:

for last; do true; done
if [ "$last" == "PREV" ]
then
    print "yes"
fi

1

试试这个:

if  [ $# -eq 4 ]  && [ "$4" = "PREV" ]
    then
            print "yes"
    fi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接