如果条件未在unix ksh中返回所需的输出-返回错误的输出
我将文件名作为参数传递给脚本,并在脚本中从该文件名提取文件扩展名 我试图通过对照列表检查所提供的扩展是否有效 有效扩展名的列表是:如果条件未在unix ksh中返回所需的输出-返回错误的输出,unix,if-statement,ksh,Unix,If Statement,Ksh,我将文件名作为参数传递给脚本,并在脚本中从该文件名提取文件扩展名 我试图通过对照列表检查所提供的扩展是否有效 有效扩展名的列表是:txt,csv,zip,* 与我的预期相反,如果$fileext包含sh,脚本仍然指示指定了有效的文件扩展名: fileext=${1##*.} if (("$fileext" == "txt")) || (("$fileext" == "csv")) || (("$fileext" == "zip")) || (("$fileext" == "*")) then
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
(())
用于整数算术。所有字符串的数值计算结果均为零,且零等于零,因此测试结果为正
您可以执行以下任一操作:
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
或
(这些代码段还应该是POSIX,因此不需要特殊的shell,如
ksh
)我猜您不希望将星号视为通配符,而是将其视为单个字符星号('*')。如果是这样,您应该能够使用我为您的帖子提供的相同ksh解决方案:
“@”是一个多模式匹配结构。在本例中,它要求字符串“txt”、“zip”、“csv”或星号作为字符“*”精确匹配
星号必须转义,否则将被视为通配符,例如:
if [[ "${fileext}" = @(*txt*) ]] ...
将匹配“txt”、“abctxt”、“txtdef”、“abctxtdef”
注意:有关POSIX/非ksh解决方案,请参阅PSkocik的答案。可能重复的“否”,它不是重复的,这里的问题是返回了错误的输出
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
if [[ "${fileext}" = @(*txt*) ]] ...