【问题标题】:If condition not returning desired output in unix ksh - returns wrong output如果条件在 unix ksh 中没有返回所需的输出 - 返回错误的输出
【发布时间】:2017-10-25 08:17:03
【问题描述】:

我将文件名作为参数传递给脚本,并在脚本内从该文件名中提取文件扩展名。

我正在尝试通过对照列表检查提供的扩展名是否有效。

有效扩展名列表为:txt、csv、zip、*。

出乎我的意料,如果$fileext 包含sh,脚本仍然表明指定了有效的文件扩展名:

fileext=${1##*.}

if (("$fileext" == "txt")) || (("$fileext" == "csv")) || (("$fileext" == "zip")) || (("$fileext" == "*"))
then
    echo "$fileext is a proper file extension"
else
    echo "$fileext is not an appropriate file extension"
fi

【问题讨论】:

标签: unix if-statement ksh


【解决方案1】:

(( )) 用于整数运算。您所有的字符串在数值上都计算为零,并且零等于零,因此测试的结果是肯定的。

您可以:

if  [ "$fileext" = "txt" ]  ||  [ "$fileext" = "csv" ]  ||  [ "$fileext" = "zip" ]  ||  [ "$fileext" = "*" ] 
then
    echo "$fileext is a proper file extension"
else
        echo "$fileext is not an appropriate file extension"
fi

或

case "$fileext" in 
    txt|csv|zip|"*") 
        echo "$fileext is a proper file extension"
        ;;
        *) 
        echo "$fileext is not an appropriate file extension"
        ;;
esac

(这些 sn-ps 还应该是 POSIX,因此不需要特殊的 shell,例如 ksh。)

【讨论】:

    【解决方案2】:

    我猜您不希望将星号视为通配符,而是将其视为单个字符星号 ('*')。如果是这样,您应该能够使用我为您的compare a substring of variable with another string in unix 帖子提供的相同 ksh 解决方案:

    fileext=${1##*.}
    if [[ "${fileext}" = @(txt|zip|csv|\*) ]]; then
        echo "$fileext is a proper file extension"
    else
        echo "$fileext is not an appropriate file extension"
    fi
    

    “@”是一个多模式匹配结构。在这种情况下,它要求字符串“txt”、“zip”、“csv”或星号作为字符“*”的完全匹配。

    星号必须转义,否则将被视为通配符,例如:

    if [[ "${fileext}" = @(*txt*) ]] ...
    

    将匹配'txt'、'abctxt'、'txtdef'、'abctxtdef'

    注意:请参阅 PSkocik 对 POSIX/非 ksh 解决方案的回答。

    【讨论】:

      猜你喜欢
      • 2016-12-20
      • 2011-11-25
      • 1970-01-01
      • 2020-12-20
      • 2013-07-23
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 2019-07-16
      相关资源
      最近更新 更多