Files
switchmon/swm
2015-02-13 13:08:43 +01:00

85 lines
1.9 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# Enable all connected montiors, disable all disconnected ones.
# Multiple monitors will be added to the right of previous ones.
#
# Author Thomas Ruoff <ThomasRuoff@gmail.com>
set -e
usage() {
echo "swm - a helper to switch connected monitors";
echo;
echo "usage: swm [monitor]";
echo;
echo "If monitor is not passed it turns on all connected devices";
echo "and lays them out next to each other in the order detected.";
echo;
echo "monitor: The string as reported by the script. If provided only";
echo "this monitor will be turned on.";
}
echoerr() { echo "$@" 1>&2; }
getFirstWord() {
awk '{print $1}'
}
linesToWords() {
awk 'BEGIN{ORS=" "} {print}'
}
wordsToLines() {
awk 'BEGIN{RS=" "} {print}'
}
without() {
comm -3 <(echo "$1") <(echo "$2")
}
if [[ $1 == "-h" ]] || [[ $1 == "--help" ]] ; then
usage
exit
fi
TARGET=$1;
CONNECTED=$( xrandr | grep " connected" | sort | getFirstWord);
DISCONNECTED=$( xrandr | grep "disconnected" | sort | getFirstWord);
POSTCMD="herbstclient reload";
echo connected devices: $(echo $CONNECTED | wordsToLines);
echo disconnected devices: $(echo $DISCONNECTED | wordsToLines);
if [[ -n "$TARGET" ]] && [[ ! "$CONNECTED" =~ "$TARGET" ]] ; then
echoerr "error: device $1 is not connected";
exit 1;
fi
FORON=${@-$CONNECTED};
FOROFF="$DISCONNECTED $(without "$CONNECTED" "$FORON")";
# turn off all disconnected monitors
XRANDR_OFF_OPTIONS="";
for mon in $FOROFF; do
XRANDR_OFF_OPTIONS+=" --output $mon --off";
done
# turn on all connected monitors
XRANDR_ON_OPTIONS="";
LAST="";
for mon in $FORON; do
XRANDR_ON_OPTIONS+=" --output $mon --auto";
if [ ! -z $LAST ]; then
XRANDR_ON_OPTIONS+=" --right-of $LAST";
fi
LAST=$mon;
done
xrandr $XRANDR_ON_OPTIONS $XRANDR_OFF_OPTIONS &&\
echo Activated monitors: ${FORON} &&\
$POSTCMD;