Of course switching devices by using the Applet is also working fine. But the cool thing about writing a script, is that it is super fast. I put mine for example on the keyboard shortcut alt+s. thus when I want to switch from headphones to speakers, I only need to press alt+s.
Anyway. Andrew said:
If you have more than two audio devices and want to swap to a
different one, you'll need to replace the logic on line 7 with some
conditionals.
That's what I did. I share it, in case someone has troubles with it:
#!/usr/bin/env bash
#sinks=($(pacmd list-sinks | grep index | \
# awk '{ if ($1 == "*") print "1",$3; else print "0",$2 }'))
sinks=($(pacmd list-sinks | grep index | \
awk '{ if ($1 == "*") print "1"; else print "0" }'))
inputs=($(pacmd list-sink-inputs | grep index | awk '{print $2}'))
#find active sink
active=0
for i in ${sinks[*]}
do
if [ $i -eq 0 ]
then active=$((active+1))
else break
fi
done
#switch to next sink
swap=$(((active+1)%${#sinks[@]}))
pacmd set-default-sink $swap &> /dev/null
for i in ${inputs[*]}; do pacmd move-sink-input $i $swap &> /dev/null; done
What I did differently is a) find the active sink in a for loop. And b) switch to the next sink by increase the index by 1. Then I modulo the result by the number of sinks. That assures that e.g. when having 3 sinks, (2+1)%3=0. Thus from sink index 2 we would switch to sink index 0.
In this way the switch allows to move upwards through the available sinks.