Konrad
Konrad

Reputation: 18585

Breaking bash script execution if passed file is of wrong extension

I have a small bash file that I used to compress PDFs and undertake some other file manipulations. I would like to break execution of this bash script if the passed file name does not have .pdf or .PDF extension.

Current approach:

# Take file name
fle_nme=$1

# Check if passed PDF file
# -ne - not equal
if ["${fle_nme: -4}" -ne ".pdf"] ||  ["${fle_nme: -4}" -ne ".PDF"]; then
        echo "Incorrect file."
        exit
fi

Current output

The script fails but without the desired message:

[me@onthebox bashStuff ERR]$ compressPDF ~/bashFun/failWithThisExtension.bad
compressPDF.sh: line 16: [.bad: command not found
compressPDF.sh: line 16: [.bad: command not found

Desired results

Upvotes: 0

Views: 76

Answers (2)

Inian
Inian

Reputation: 85560

Fix the if-conditional in bash, put spaces around [, ] and always remember to quote your variables and remember -ne is for integer comparisons and not for string comparison.

fle_nme="$1"
if [ "${fle_nme: -4}" != ".pdf" ] ||  [ "${fle_nme: -4}" != ".PDF" ]; then

(or) you have a relatively recent version of bash you can set the nocasematch option available which will work for both .pdf and .PDF

shopt -s nocasematch
if [[ "${fle_nme: -4}" != ".pdf" ]]; then
..

shopt -u nocasematch

Also worth adding that, the shell option you are setting needs to be disabled soon after the comparison is done. If not the option will be propagated to the rest of the script which might affect your other string comparisons.


As a side note, the best way to extract the extension from the filename would be to use parameter expansion syntax like below, this way you need not worry about the number of characters comprising of the file extension

shopt -s nocasematch
if [[ "${fle_nme##*.}" != "pdf" ]]; then

Upvotes: 2

Jack
Jack

Reputation: 6158

That is not the correct syntax. It should be:

if [ "${fle_nme: -4}" != ".pdf" -a "${fle_nme: -4}" != ".PDF" ]; then

As Inian said, you need spaces. Also, -ne is for numeric comparisons. Finally, use -a for the and inside the brackets.

Inian's second option is best, if you also want to allow .Pdf and .pDf and all other such capitalation.

Upvotes: 1

Related Questions