显示具有特定扩展名的所有文件的文件名

Display file name of all files with certain extension

我想要的是让用户使用 zenity 从任何地方 select 一个文件,脚本将检测文件扩展名,例如 (.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