如果条件未在 unix ksh 中返回所需的输出 - returns 错误输出
If condition not returning desired output in unix ksh - returns wrong output
我将文件名作为参数传递给脚本,并在脚本中从该文件名中提取文件扩展名。
我正在尝试通过对照列表检查所提供的扩展名是否有效。
有效扩展列表为: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
或
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
。)
我猜您不希望将星号视为通配符,而是将星号视为单个字符星号 ('*')。如果是这样,您应该能够使用我为您的 compare a substring of variable with another string in unix post:
提供的相同 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/non-ksh 解决方案。
我将文件名作为参数传递给脚本,并在脚本中从该文件名中提取文件扩展名。
我正在尝试通过对照列表检查所提供的扩展名是否有效。
有效扩展列表为: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
或
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
。)
我猜您不希望将星号视为通配符,而是将星号视为单个字符星号 ('*')。如果是这样,您应该能够使用我为您的 compare a substring of variable with another string in unix post:
提供的相同 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/non-ksh 解决方案。