How do you check if a file ends in a certain file extension in bash? - eviltoast

Seriously. There doesn’t seem to be a way to do this. Every thing I ever try I just get bad substitution errors. The internet is full of people posting code that’s supposed to compare file extensions but none of it works. I’ve spent all morning trying everything I could find. I already gave up and I’m making this progeam in python instead but now I’m curious. How tf do you actually compare file extensions? If I have a folder fill of files and I want to run a command only on the png files, there seems to be no way to actually do this.

If someone posts “[[ $file == *.txt ]]” I’m going to fucking scream because THAT DOES NOT WORK. IT’S NOT VAILD BASH CODE.

  • GenderNeutralBro@lemmy.sdf.org
    link
    fedilink
    English
    arrow-up
    2
    arrow-down
    1
    ·
    edit-2
    5 months ago

    If someone posts “[[ $file == *.txt ]]” I’m going to fucking scream because THAT DOES NOT WORK. IT’S NOT VAILD BASH CODE.

    This is valid bash code.

    Do you understand how string substitution works? In this example, “file” is the name of a variable, and $file substitutes its value. If you have not set the value of file, then it won’t work.

    Edit: you should, as a rule of thumb, quote your variables. So "$file" instead of just $file. Quoting prevents some weird behavior with whitespace and special characters in the value. But either way, this is valid code and will work in the general case.