Reputation: 1940
i'm trying to create a bash script which lets me toggle external screens based on which screens are connected to my laptop (I have two ports). To be honest, my expertise in bash is limited, so this could also be a logical bash mistake. I have the following script:
#!/bin/bash
HDMI=$(xrandr | grep 'HDMI' | cut -d ' ' -f 1)
LVDS=$(xrandr | grep 'LVDS' | cut -d ' ' -f 1)
VGA=$(xrandr | grep 'VGA' | cut -d ' ' -f 1)
HDMI_CON=$(xrandr | grep "$HDMI connected")
HDMI_DIS=$(xrandr | grep "$HDMI disconnected")
VGA_CON=$(xrandr | grep "$VGA connected")
VGA_DIS=$(xrandr | grep "$VGA disconnected")
if [ VGA_CON ] && [ HDMI_CON ]
then
echo "VGA CON, HDMI CON"
elif [ VGA_CON ] && [ HDMI_DIS ]
then
echo "VGA CON, HDMI DIS"
elif [ VGA_DIS ] && [ HDMI_CON ]
then
echo "VGA DIS, HDMI CON"
else
echo "VGA DIS, HDMI DIS."
fi
What happens is that VGA_CON && HDMI_CON always return true, which results in my script always thinking both displays are connected. Anyone who can enlighten me regarding whats happening?
Upvotes: 0
Views: 443
Reputation: 1030
By using the $()
syntax, you are setting those variables equal to the output strings generated by xrandr
. A better option might be something like:
#!/bin/bash
HDMI=$(xrandr | grep 'HDMI' | cut -d ' ' -f 1)
LVDS=$(xrandr | grep 'LVDS' | cut -d ' ' -f 1)
VGA=$(xrandr | grep 'VGA' | cut -d ' ' -f 1)
HDMI_CON=$(xrandr | grep -q "$HDMI connected" ; echo $?)
HDMI_DIS=$(xrandr | grep -q "$HDMI disconnected" ; echo $?)
VGA_CON=$(xrandr | grep -q "$VGA connected" ; echo $?)
VGA_DIS=$(xrandr | grep -q "$VGA disconnected" ; echo $?)
if [[ $VGA_CON -eq 0 && $HDMI_CON -eq 0 ]]
then
echo "VGA CON, HDMI CON"
elif [[ $VGA_CON -eq 0 && $HDMI_DIS -eq 0 ]]
then
echo "VGA CON, HDMI DIS"
elif [[ $VGA_DIS -eq 0 && $HDMI_CON -eq 0 ]]
then
echo "VGA DIS, HDMI CON"
else
echo "VGA DIS, HDMI DIS."
fi
This sets those variables equal to the result code of the grep (0 for found, 1 for not). I left your same basic logic for the output in place, but that could possibly be enhanced depending on what xrandr
outputs.
Upvotes: 1