Why does redirecting output affect the result of a test in bash?
-
11-12-2019 - |
Question
I'm trying to write a script to launch xfce and xbmc in their own x sessions.
To do this I'm setting the DISPLAY
value, running the first one in the background and waiting until I get a successful return from xset q
. Then I change DISPLAY
and do the same for the other.
I'm writing this piece by piece to check I've got the syntax right for each part and the part I'm stuck on is the 'waiting until I get a successful return from xset q
.
export DISPLAY=":0.0"
while [[ ! `xset q` ]]
do
echo -n "."
done
This code seems to work so when XFCE is running it exits immediately and when it is not it sits there printing .xset: unable to open display ":0.0"
However I don't want to see the output of xset
so I'm trying to redirect its output.
export DISPLAY=":0.0"
while [[ ! `xset q > /dev/null 2>&1` ]]
do
echo -n "."
done
Adding this redirection however seems to break the detection, and regardless of whether XFCE is running or not it just sits there printing dots.
I've tested the two commands on their own and in a shell script on their own they both work as I expect, returning 1 when XFCE is not running and 0 when it is.
Can anyone explain why putting that command inside of [[ ! `…` ]]
breaks the while
test and how I could rewrite this while
loop correctly?
(Running on Arch)
Solution
The problem is that you're not testing the return code of xset
at all, you processing it's output. When you redirect the output to /dev/null
, the expression in backticks doesn't return anything, it's as if you had:
while [[ ! '' ]] ...
which will always run the while
body.
What you should be doing is:
while ! xset q > /dev/null 2>&1
do
...
done