2

I prepared a little bash script to toggle the visibility of my hidden OS X files.

if (defaults write com.apple.finder AppleShowAllFiles FALSE); then
    defaults write com.apple.finder AppleShowAllFiles TRUE
elif (defaults write com.apple.finder AppleShowAllFiles TRUE); then
    defaults write com.apple.finder AppleShowAllFiles FALSE
fi

killall Finder

When hidden files are invisible, the script successfully makes them visible but afterwards, when I re-run the script to make the hidden files invisible again, it fails and does nothing.

Where am I going wrong?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Can Sürmeli
  • 249
  • 1
  • 3
  • 12
  • 1
    Did you try adding debug information to 'see' what the script thinks it is doing? Did you try running it with the dash x option (e.g. change the first two lines to `#!/usr/bin/env bash` and the second line to `set -x`). – Hennes Jul 13 '13 at 14:06
  • I got the following output + defaults write com.apple.finder AppleShowAllFiles FALSE + defaults write com.apple.finder AppleShowAllFiles TRUE + killall Finder It seems the if-else part is not working at all – Can Sürmeli Jul 13 '13 at 15:22

1 Answers1

6

In the if conditions you should use the defaults read command, and not write. Otherwise the result is always true and of course the elif never runs.

Also, that is not the syntax for if conditions. You should use:

if [ $(command) == "TRUE" ]; then

But in this case, perhaps something like this would be less verbose:

STATUS=$(defaults read com.apple.finder AppleShowAllFiles)
case "$STATUS" in
    "TRUE") OPTION="FALSE" ;;
    "FALSE") OPTION="TRUE" ;;
esac
defaults write com.apple.finder AppleShowAllFiles $OPTION

killall Finder
Paulo Almeida
  • 736
  • 3
  • 4
  • 1
    That read/write situation came to my mind as well yesterday after debugging. Nice spotting. Thanks for your solution as well. You've been very helpful. – Can Sürmeli Jul 14 '13 at 09:00