This short script allows the Play/Pause keyboard key to be also used to start Spotify (or any player of your choice with a bit of tweaking). I'm using Cinnamon's settings to reassign keys, but other distros may also have this feature
- Download/copy the script somewhere on your system
chmod +x ./spotifyPause.sh
to make it runnable- Add the new keybinding [Cinnamon only]
- Open
cinnamon-settings keyboard
(you can search for "Keyboard" in the start menu search if you don't like terminals) - Navigate to
Shortcuts
>Custom shortcuts
Add custom shortcut
Name=[doesn't matter] Command=[path to the script]- Click the shortcut's name in the top list (it should already be selected)
- Click on one of the
unassigned
slots below and press the Play/Pause button of your keyboard - If a warning dialog appears because the key is already assigned, press
Continue
. A key cannot be programmed to do two actions, but the script will send a Play/Pause signal when executed (2nd line), thus removing the need for the old keybinding
- Open
- Done !
What I'm explaining below is quite basic. Only take the time to read it if you don't know bash or Linux in general !
#!/bin/bash
Shebang: When a file is
chmod +x
ed, Linux considers it executable. This line tells the OS which binary should be used to interpret(=run) the file, here it isbash
.
dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause
Play/Pause signal: This sends a Play/Pause signal to Spotify, which is what the default keybinding does. source
pidof spotify
if [ $? -ne 0 ]
then
nohup spotify &
fi
Starting Spotify:
The first line runs a command which returns the PID (process id) of a process whose name is
spotify
. Here, we don't really care about it, you'll see why.Then, we encounter an
if
statement, which checks if the variable$?
is different from0
.$?
is the status/exit code of the last command that was run. All Linux processes must return such a code when stopping. The convention is that0
is returned when everything worked fine. In this case, if$? -ne 0
, this implies thatpidof spotify
had encountered an error, which means that no process matching the namespotify
was found. In other words, the code inside theif
statement only runs if Spotify isn't running.This code,
nohup spotify &
, starts Spotify as a background process, thanks tonohup
and&
. Here, "background" means that the script won't pause and wait for Spotify to stop, which would have been the default behavior if we just typedspotify
.