Pipe output of grep to a variable
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.
Solution 1:
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.
Solution 2:
Try
if [[ $(defaults read com.apple.Finder | grep "AppleShowAllFiles") == "AppleShowAllFiles = TRUE;" ]]; then
defaults write com.apple.Finder AppleShowAllFiles FALSE
else
defaults write com.apple.Finder AppleShowAllFiles True
fi
killall Finder
$(...)
executes the part between ()
and replaces it with the result. So you could also do
ASAF=$(defaults read com.apple.Finder | grep "AppleShowAllFiles")
to assign the result to $ASAF
.
PS: I also changed two other things in your script
- use
[[
for the test part (has more functionality than[
and is builtin in bash - use
==
to compare strings (=
is for assignments only`)