macOS Finder – Programmatically Change Hide Extension Setting for Files

bashfindermacos

For some reason, when I do a bash operation on a list of files (i.e. ls | cat -n | while read n f; do mv "$f" `printf "name-%02d.png" $n`; done, the "Hide extension" setting becomes enabled on all of them, and I have to manually uncheck that via "Get info". How can I avoid this, or fix it programmatically?

EDIT: The files I was operating on were native screenshots and thus already had their extensions hidden. My bad!

Best Answer

Hmmm, that sounds really odd. I just ran your sample code on some test files and it didn't alter the Hide extension flag at all. Are you sure the files didn't already have that option checked before you ran your command? Have you tried creating a few fresh files, verifying manually that none have that option selected, and then running your command on them?

I can't help in terms of the "how to avoid this" part of your question, as I can't manage to recreate your problem on my end. But you can disable that setting programmatically. If you have Xcode installed, you can do the following:

# Disables "Hide extension" for all visible files in current directory
for file in *; do
    SetFile -a e "$file"
done

Note that if you ever want to reverse the process (i.e. turn on the setting), you can do so by changing the lowercase e to an uppercase E.

# Enables "Hide extension" for all visible files in current directory
for file in *; do
    SetFile -a E "$file"
done

If you don't have Xcode installed, see this answer on superuser for instructions on how to do the same thing using AppleScript.

By the way, you should try to avoid parsing the output of ls like you have done in your example. It can cause problems if any of the files you are processing contain a newline character in their filename. This is particularly important if you ever write a script that will be processing files which you have not created yourself (as you won't know how they are named). See Why you shouldn't parse the output of ls(1) for details.