Search code examples
macosbashshellosx-mountain-lion

Mac shell script - using a boolean value straight from a condition check


I am writing a shell script to toggle the display of hidden files on Mac OSX Mountain Lion. But after searching around, I couldn't find an answer to this: Is it possible to take the boolean of a condition expression and use it straight? For example in java, I would have done print(1 == 0) and get the result false. If it is possible, how?

Please note that I am not asking for the "if-else" method that I only could find on Google. Below is the current script that I have wrote so far, with problems in line 2.

#!/bin/sh
defaults write com.apple.Finder AppleShowAllFiles [$(defaults read com.apple.Finder AppleShowAllFiles) = 0]
killall Finder && open /System/Library/CoreServices/Finder.app

Solution

  • No not possible directly.

    You could do something silly like

    #!/bin/sh
    defaults write com.apple.Finder AppleShowAllFiles $(defaults read com.apple.Finder AppleShowAllFiles | grep -q 0 && echo true || echo false)
    killall Finder && open /System/Library/CoreServices/Finder.app
    

    but it's best to just use if..then or a switch:

    #!/bin/sh
    case "$(defaults read com.apple.Finder AppleShowAllFiles)" in
      1) val=true ;;
      *) val=false ;;
    esac
    defaults write com.apple.Finder AppleShowAllFiles $val
    killall Finder && open /System/Library/CoreServices/Finder.app