如果条件没有在unix ksh中返回所需的输出 - 返回错误的输出

时间:2017-05-24 20:12:38

标签: unix if-statement ksh

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

我正在尝试通过针对列表进行检查来验证提供的扩展是否有效。

有效扩展程序列表为:txtcsvzip*

根据我的预期,如果$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

2 个答案:

答案 0 :(得分:2)

(( ))用于整数运算。所有字符串的数值均为0,零等于零,因此测试结果为正。

你可以这样做:

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

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

答案 1 :(得分:0)

我猜你不希望星号被视为通配符,而是作为单个字符星号('*')。如果是这样,您应该能够使用我为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解决方案的回答。