我想让用户使用zenity从任何地方选择一个文件,脚本将检测文件扩展名,例如(.tar.gz)或(.zip),并相应地对它们执行操作。下面是一个例子。
#! /bin/bash
FILE=$(zenity --file-selection --title="Select a file to check")
echo "File: $FILE"
if [ "$FILE" = "*.zip" ]
then
echo "File that is a .zip found"
FILENAMENOEXT="${FILE%.*}"
echo "Filename with extention $FILENAMENOEXT"
#Perform xx action to $FILE if it is a zip
elif [ "$FILE" = "*.tar.gz" ]
then
echo "File is a .tar.gz found"
FILENAMENOEXT="${FILE%.tar.*}"
echo "Filename with extention $FILENAMENOEXT"
#Perform xx action to $FILE if it is a t.tar.gz
else
echo "File is neither .zip nor .tar.gz"
fi
echo "test $FILENAMENOEXT"
基本正确。
你需要使用[[
来做模式匹配,引号禁用模式匹配。
把[ "$FILE" = "*.zip" ]
换成[[ "$FILE" = *".zip" ]]
,把[ "$FILE" = "*.tar.gz" ]
换成[[ "$FILE" = *".tar.gz" ]]
。
您也可以使用case
语句来代替if
/elif
。
case "$FILE" in
*.zip)
echo "File that is a .zip found"
;;
*.tar.gz)
echo "File is a .tar.gz found"
;;
*)
echo "File is neither .zip nor .tar.gz"
;;
esac