Search code examples
linuxbashshellzenity

Display file name of all files with certain extension


What I want is for the user to select a file from anywhere using zenity, and the script will detect the file extension, for example (.tar.gz) or (.zip), and perform actions on them accordingly. Here's an example.

#! /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"

Solution

  • This is almost correct.

    You need to use [[ to do pattern matching and quotes disable pattern matching.

    So instead of [ "$FILE" = "*.zip" ] you want [[ "$FILE" = *".zip" ]] and instead of [ "$FILE" = "*.tar.gz" ] you want [[ "$FILE" = *".tar.gz" ]].

    You could also use a case statement instead of 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