Pipe output of grep to a variable

bashcommand linescriptterminal

I need to be able to write whether the test for a grep is either TRUE or FALSE to a variable so I can use it later

For the following, if I run

defaults read com.apple.Finder | grep "AppleShowAllFiles"

on my system, it would return

AppleShowAllFiles = FALSE;

Cool. So now I want to pipe this response to a test of some kind. This is where I get stuck.

I think if I can pipe/assign this output to a specified variable, I would be able to run a test on it. Now, just say, I've assigned the value of this output to a variable, in this case I will use $ASAF as my variable, I can run it in a test like this

if [ $ASAF = "AppleShowAllFiles = TRUE;" ]; then  
    defaults write com.apple.Finder AppleShowAllFiles FALSE  
    killall Finder  
else  
    defaults write com.apple.Finder AppleShowAllFiles True  
    killall Finder  
fi

If there is some other way to do this, I would be more than open to options. I've not had to do something like this for a while, and I'm a bit stumped. I searcehd Google a bit, but it was all answers without explanations and using the return value of 0 or 1. I think the returned output being assigned to a variable would be more appropriate, as then I can use it over and over in the script as need be.

Best Answer

You don't need to use grep at all:

[[ $(defaults read com.apple.finder AppleShowAllFiles) = 0 ]] && bool=true || bool=false
defaults write com.apple.finder AppleShowAllFiles -bool $bool
osascript -e 'quit app "Finder"'

defaults read prints boolean values as 1 or 0. For example True or YES as a string is also interpreted as a boolean value, but -bool true specifies the value to be actually boolean.