0

I have the following line of code in a bash script:

# Is there an external monitor connected via HDMI?
has_external=$(xrandr 2> /dev/null | grep -q 'HDMI[0-9] connected')

The output of xrandr could contain this:

HDMI1 connected (normal left inverted right x axis y axis)
HDMI2 disconnected (normal left inverted right x axis y axis)
HDMI3 disconnected (normal left inverted right x axis y axis)

For the life of my I can't figure out why the has_external variable always evaluates to true, even if "HDMI1 connected" is not in the output of xrandr. Any ideas?

Matt
  • 8,758
  • 4
  • 35
  • 64
  • 4
    Command substitution stores **output**, not exit status. `-q` suppresses output. – Charles Duffy Jan 27 '17 at 21:01
  • 2
    thus, `has_external` will always have the same empty value after the code in question has run. I would appreciate it if you could edit your question to show how you're determining it to "evaluate to true". – Charles Duffy Jan 27 '17 at 21:02
  • 2
    ... and consequently you probably wanted `xrandr 2> /dev/null | grep -q 'HDMI[0-9] connected'; has_external=$?`? – dhke Jan 27 '17 at 21:02
  • Brilliant, thanks @CharlesDuffy and dhke -- I assumed the exit status was stored in the variable. – Matt Jan 27 '17 at 21:12

1 Answers1

1

I am not sure how you evaluate the variable has_external that it happens to be "always true" - that's probably the source of your problem.

You can do the same check with a condition like:

if xrandr 2> /dev/null | grep -q 'HDMI[0-9] connected'; then
   # HDMI present
fi

Or:

xrandr 2> /dev/null | grep -q 'HDMI[0-9] connected'
rc=$?
if [[ $rc == 0 ]]; then
    # HDMI present
fi
P.P
  • 117,907
  • 20
  • 175
  • 238
  • 1
    I'd suggest `(( rc == 0 ))` if you want bash-only syntax, or `[ "$rc" -eq 0 ]` otherwise. Also, as a best practice, appending `...; rc=$?` on the same line whose exit status you're capturing prevents additional logging or other changes from disrupting that exit status before it's captured if the folks making those edits aren't paying enough attention to context to notice the strict ordering dependency. – Charles Duffy Jan 27 '17 at 21:08