Bash script to switch Pulseaudio sinks

08 December 2024 • Tags: linuxbashpulseaudio

Who doesn’t love using the keyboard even for simple things like switching the output (or sink as pulseaudio calls it) for you audio? My setup is a set of external speakers, a monitor with rather bad speakers and plugged into the monitor at all time my headphones. That makes three sinks which makes my script a bit more complicated than a simple toggle to the other (i.e. IDLE sink) would be.

The obvious other use-case for this script is one systems where you don’t have a display.

#!/bin/env sh

# get the names and give each a number
sinks=`pactl list sinks | grep Name | grep -n Name`
# echo with " to get the newlins properly and find which we currently use
current_sink_number=`echo "$sinks" | grep "\$(pactl get-default-sink)" | cut -d: -f 1`

# modulo on current sink + 1
new_sink_number=$((($current_sink_number % `echo "$sinks" | wc -l`) + 1))

# find id of the next sink
new_sink=`echo "$sinks" | sed -En "/$new_sink_number:/ s/.*Name: (.*)/\1/p;"`
pactl set-default-sink $new_sink

# get name of the default sink and make it look pretty
new_sink_name=`pactl list sinks | sed -En "                # -n to be quiet, we use print below
	N                                                  # add the next line
	/Name: $(pactl get-default-sink).*Description/{    # match the pair of lines with Name and Description
		s/(Stereo|Analog|Digital|Controller).*//   # remove some noise
		s/.*Description: (.*)/\1/p                 # match the name and print it
	}"`
notify-send "Using sink $new_sink_name"

If your Linux skills are still basic, here’s how to install and use the script: Put the code into bin/switch-pulseaudio-sink.sh then chmod 700 bin/switch-pulseaudio-sink.sh to make the file executable and lastly assign it some keyboard shortcut in your desktop manager. In xfce4 I’m using Alt-Shift-S (s for sink) but you might have extra multimedia keys on your keyboard that you could re-assign with acpi, in that case /etc/acpid/handler.sh is most likely on your system available for this.