Reputation: 57
I am passing a file name as an argument to a script and inside the script I'm extracting the file extension from that file name.
I am trying to verify whether the extension provided is valid by checking it against a list.
The list of valid extensions is: txt
, csv
, zip
, *
.
Against my expectations, if $fileext
contains sh
, the script still indicates that a valid file extension was specified:
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
Upvotes: 2
Views: 71
Reputation: 60067
(( ))
is for integer arithmetic. All your strings evaluate to zero numerically and zeros are equal to zeros, hence the positive result of the test.
You can do either:
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
or
case "$fileext" in
txt|csv|zip|"*")
echo "$fileext is a proper file extension"
;;
*)
echo "$fileext is not an appropriate file extension"
;;
esac
(These snippets should additionally be POSIX and therefore not require special shells such as ksh
.)
Upvotes: 2