John Smith
John Smith

Reputation: 87

How to get Applescript input to run Terminal Command

I am frequently switching between school computers and have a preference to have the hidden files shown, however, not everyone does. Normally I use the

"defaults write com.apple.finder AppleShowAllFiles -bool true"

command, however, it would be very convenient if I could just run some Applescript, instead of manually copying the text into the Terminal and then redoing this when I'm done. So what I am trying to accomplish is the receive user input as to whether they want to show all files or not and then run that command. Doing some initial research on Applescript I was able to figure out some basic idea of how I would structure it. The below code is wrong, so please excuse by noob mistakes.

(choose from list {"Hide", "Show"} ¬
    with prompt "Do you want to hide or show hidden files?")
if "Hide" then
    do shell script "defaults write com.apple.finder AppleShowAllFiles -bool False"
else 
    do shell script "defaults write com.apple.finder AppleShowAllFiles -bool True"
end 

I can get up to the user dialogue box, however, when I try and input a choice, it replies: "Can’t make "Hide" into type boolean.". If someone could help me out show me what I need to change then that would be greatly appreciated.

Thanks, Michael.

Upvotes: 0

Views: 1554

Answers (2)

Darrick Herwehe
Darrick Herwehe

Reputation: 3722

Choose from list returns a list (or False if the user cancels). Do this to coerce the list into a string:

(choose from list {"Hide", "Show"} ¬
    with prompt "Do you want to hide or show hidden files?") as string

Make sure you keep the parentheses, otherwise, as string will coerce your prompt string, and you will still receive a list back.

Upvotes: 0

Lri
Lri

Reputation: 27613

choose from list returns a list of the selected items.

choose from list {"Hide", "Show"} with prompt "Do you want to hide or show hidden files?"
if result is {"Show"} then
    do shell script "defaults write com.apple.finder AppleShowAllFiles -bool true"
else
    do shell script "defaults write com.apple.finder AppleShowAllFiles -bool false"
end if
quit application "Finder"

I use a script like this to toggle showing hidden files:

do shell script "x=$(defaults read com.apple.finder AppleShowAllFiles)
[ $x = 1 ] && b=false || b=true
defaults write com.apple.finder AppleShowAllFiles -bool $b"
tell application "Finder"
    quit
    delay 0.1 -- without this delay Finder was not made frontmost
    launch -- open Finder in the background
    delay 0.1 -- without this delay there was sometimes a "connection is invalid" error
    activate -- make Finder frontmost
    reopen -- open a new default window
end tell

Upvotes: 3

Related Questions