Batocera scripts

If you are looking for how scripts behaved in v37 and below, refer to the legacy scripts page.

You can opt to have scripts launched at various points in Batocera. This will change the location you save the script to and how it opens.

When booting and shutting down, Batocera checks for scripts three times at different stages in the boot/shutdown process:

When these scripts are executed, Batocera sends the first argument to the script as start when Batocera is booting and stop when Batocera is shutting down. Putting code into cases or other checks for these argument values will cause that code to only be executed when booting or shutting down, otherwise code will be executed on both boot and shutdown.

In Batocera v32 and higher, scripts can be launched early in the boot process, before much of Batocera has even begun loading. This is done by storing the script in the boot partition at /boot/ Keep in mind that this script will be limited to more basic commands/modules, as most things have not loaded yet. The filename must be otherwise it will not be checked.

Precisely, this is the first thing executed once init.d has begun. This is before the network/share population/IR remote daemon have even loaded so capabilities are limited. Check /etc/init.d to see the exact order of all the modules have been loaded in (S00bootcustom is when the /boot/ is executed).

This can be used to effectively patch and/or override the modules loaded by Batocera. Here are some examples that are only possible with this method:

  • Customize or disable S33disablealtfn to allow a certain text mode console on a particular TTY session.
  • Run fsck -a or e2fsck -p to harden the file system against data corruption in the case of a power cut/disconnection.

In Batocera v35 and higher, scripts can also be launched after /userdata is mounted in the boot process, before the splash video plays (and before Emulationstation has begun loading). It has to be placed to /boot/ and is executed directly by the bash interpreter (no executable flag required).

This is the only init.d scripts that doesn't execute in background. So if you use a sleep timer for example, the script will halt till the time from sleep command is up! Be aware of endless do-while loops! Get familiar with shell commands and the usage of the ampersand m( &

Sometimes you just want to fire up one script after successfully booting, for example when you want to start up a VPN or other after-boot tasks. In order to do this, create a script text file at /userdata/system/ Be aware that the script will be executed independently of the executable (x) attribute being set to the script file or not!

This script is the very last one that will be invoked by Batocera at boot time after EmulationStation has launched (check /etc/init.d/ to see all the modules that are loaded before then, S99userservices (previously S99custom in Batocera v38 and below) is when the user script is launched). The filename must be otherwise it will not be checked.

Make sure your script ends with Unix line terminators (LF), not Windows-style line terminators (CR/LF) otherwise the script will not launch. Use a real text editor to edit your scripts, especially if you edit them under Windows.

A simple custom script as an example
# Code here will be executed on every boot and shutdown.
# Check if security is enabled and store that setting to a variable.
case "$1" in
        # Code in here will only be executed on boot.
        enabled="$(/usr/bin/batocera-settings-get system.samba.enabled)"
        if [ "$enabled" = "0" ]; then
            echo "SMB services: disabled"
            exit 0
        # Code in here will only be executed on shutdown.
        echo -n "Shutting down SMB services: "
        kill -9 `pidof smbd`
        rm -f /var/run/samba/
        echo "done"
        # Code in here will executed (when?).
        echo "SMB services: reloaded"
        # Code in here will be executed in all other conditions.
        echo "Usage: $0 {start|stop|restart}"
exit $?

Batocera 5.23 and higher supports running a script right before a game launches and/or after a game is exited. Here are some examples:

  • Automatic controller setup
  • Automatic scraping for new games
  • Change screen resolution (though it might be better to use switchres for this)
  • Sync savestates to an external/network device
  • … give me your idea here

Place an executable script (can have any filename) with the correct setted shebang (first line!) or an executable binary into directory /userdata/system/scripts/.

Game start/stop event scripts must be marked as executable with the chmod +x command. For example:

# Open up a text editor to create your script:
nano /userdata/system/scripts/
# Write in your script, save and exit.
# Then to add the executable bit to it:
chmod +x /userdata/system/scripts/

This means that if your userdata partition is of the NTFS, exFAT or older file system that are missing the executable bit functionality, it will fail to execute.

You can add as many subfolders as you want, every script placed there will be executed. To distinguish between START or STOP condition the first argument parsed in the script have either of these flags:

  • gameStart is passed to your scripts if you select a game from EmulationStation (Game Starts!)
  • gameStop is passed to your scripts if you are going back from a game to EmulationStation (Game Stops!)

If you do not set cases for first argument, then the script is executed on every start and on every end of a game.

Table of parsed arguments in correct order and their functions:

Arg no. Parsed Parameter Usage
1 gameStart or gameStop To distinguish between START or STOP condition
2 systemName The system shortname as is in es_system.cfg, eg. atari2600
3 system.config['emulator'] The emulator settings, eg. libretro
4 system.config['core'] The emulator core you have chosen, eg. stella
5 args.rom The full rom path, eg. /userdata/roms/atari2600/Mysterious Thief, A (USA).zip

At first create the directory where the scripts need to be set up. Connect through SSH and type mkdir /userdata/system/scripts. After this we can set up our first script by typing nano /userdata/system/scripts/ The filename can be anything readable by bash.

Here's the template script:
# This is an example file of how gameStart and gameStop events can be used.
# It's good practice to set all constants before anything else.
# Case selection for first parameter parsed, our event.
case $1 in
        # Commands in here will be executed on the start of any game.
        echo "START" > $logfile
        echo "$@" >> $logfile
        # Commands here will be executed on the stop of every game.
        echo "END" >> $logfile

Now you can see a log file created /tmp/scriptlog.txt, that parsed all arguments in this file. This is just a small test of course. You can check out the SSH page and the usage of batocera-settings page for general and Batocera-specific commands.

In case Batocera's provided scripting functionality is not sufficient, ES itself also triggers scripts of its own volition. Extra scripts can be created at /userdata/system/configs/emulationstation/scripts/<event name>/<script>.sh; unlike regular Batocera scripts the event named will trigger all scripts in the respective event folder. For instance, to have a script execute at every game-start event, it must be placed in /userdata/system/configs/emulationstation/scripts/game-start/.

All EmulationStation scripts must be marked as executable with the chmod +x command. For example:

# Open up a text editor to create your script:
nano /userdata/system/configs/emulationstation/scripts/game-start/
# Write in your script, save and exit.
# Then to add the executable bit to it:
chmod +x /userdata/system/configs/emulationstation/scripts/game-start/

This means that if your userdata partition is of the NTFS, exFAT or older file system that are missing the executable bit functionality, it will fail to execute.

Event name Arguments Notes
game-start ROM name rom, ROM path basename (arguments described below) When a game starts. Nearly identical to Batocera's gameStart, however this doesn't include as much information and only triggers when it's ES itself that starts it.
game-end N/A When a game ends. Nearly identical to Batocera's gameStop, however this only triggers when it's ES itself that ends it.
game-selected getSourceFileData()→getSystem()→getName(), getPath(), getName() New to Batocera v33. Whichever game is currently being hovered over. Includes games shown during the screensaver.
system-selected System getSelected()→getName() New to Batocera v33. Whichever system is currently being hovered over in the system list.
theme-changed Theme being switched to theme_set→getSelected(), Previous theme oldTheme When a different theme is selected. Mostly used for theme/element reloading.
settings-changed N/A When a system setting is saved.
controls-changed N/A When a controller mapping is saved from the CONTROLLER MAPPING menu.
config-changed N/A Whenever any configuration, be it system settings or controller mappings, is changed.
quit N/A When the system is told to do a regular shutdown.
reboot N/A When the system is told to do a reboot.
shutdown N/A When the system is told to do a fast shutdown.
sleep N/A When the system is told to sleep.
wake N/A When the system is told to wake from sleep.
achievements with arguments described below When a RetroAchievement is unlocked - new to Batocera v38

EmulationStation sends different arguments to these scripts based on the event type. For game-related events:

Arg no. Parsed parameter Usage
1 system The current system of the game.
2 rom The filename of the current game.
3 romname The name of the game as specified in its metadata.

All events need to be added here.

This script is an example of an EmulationStation game-selected script for controlling the Pixelcade display. More robust results with the Pixelcade may be achieved with the Pixelcade Batocera scripts.
# Save the arguments into variables.
# Convert an argument into another value.
if [[ "${system}" == "fbneo" ]]; then
# Switch case for certain systems.
case ${system} in
# Execute this part every time this event triggers.
curl -G \
        --data-urlencode "t=${romname}" \${system}/`basename ${rom}`

Friendly reminder that older examples have now been moved to the legacy scripts page.
while true; do
    currenthour=$(date +%k%M)
    if [ $currenthour -eq 2355 ]; then
        shutdown -h now
    sleep 30
  • Disable a specific network interface (e.g. eth0, eth1, etc.):
ifconfig eth1 down
# by cyperghost for batocera
echo "END Script!" >> $testfile
echo "Parameter: $@" >> $testfile
echo "Systemname: $1" >> $testfile
echo "Emulatorcore: $2" >> $testfile
echo "ROM: $(basename "$3")" >> $testfile 
[[ "$4" == "libretro" ]] && echo "You are free!" >> $testfile || echo "No hotkey is pure hell eh??" >> $testfile
case "$1" in
    # LED init
    echo "$LED1" > /sys/class/gpio/export
    echo "$LED2" > /sys/class/gpio/export
    echo out > /sys/class/gpio/gpio$LED1/direction
    echo 0 > /sys/class/gpio/gpio$LED1/value
    echo out > /sys/class/gpio/gpio$LED2/direction
    echo 1 > /sys/class/gpio/gpio$LED2/value
    #Button init
    echo "$SHUTDOWN" > /sys/class/gpio/export 
    echo "in" > /sys/class/gpio/gpio$SHUTDOWN/direction 
    #This loop continuously checks if the shutdown button was pressed 
    #It sleeps as long as that has not happened. 
    buttonstate1=$(cat /sys/class/gpio/gpio$SHUTDOWN/value)
    shutdownSignal=$(cat /sys/class/gpio/gpio$SHUTDOWN/value)
    while [ $shutdownSignal = $buttonstate1 ]; do 
        shutdownSignal=$(cat /sys/class/gpio/gpio$SHUTDOWN/value)
        sleep 0.5
    shutdown -h now 
      #unexport all GPIOs
       #echo "$SHUTDOWN" > /sys/class/gpio/unexport 
       echo "$LED1" > /sys/class/gpio/unexport 
       echo "$LED2" > /sys/class/gpio/unexport 
exit $?
# disable auto load/save state inside ES
# add 'global.retroarch.savestate_auto_load=true'
# to your batocera.conf
# by cyperghost aka lala for BATOCERA
# download this script to '/userdata/system/scripts' and set executable bit
rom_no_ext="$(basename "${5%.*}")"
[[ "$(batocera-settings get global.autosave)" -eq 1 ]] && exit
[[ "$(batocera-settings get global.retroarch.savestate_auto_load)" == "true" ]] || exit
if [[ $1 == "gameStart" ]]; then
    file="$(/bin/ls "$sav_path/$rom_no_ext."* -turR1A | tail -1)"
    [[ -n "$file" ]] || exit
    [[ "${file##*.}" == "png" ]] && file="${file%.*}"
    [[ -f "$file" ]] || exit
    cp -f "$file" "$sav_path/$"
if [[ $1 == "gameStop" ]]; then
    rm -f  "$sav_path/$"
  • Faff about with audio settings.
case "$1" in
        # Get the current audio profile.
        defaultprofile="$(batocera-audio get-profile)"
        # Get the current audio device.
        defaultaudio="$(batocera-audio get)"
        # Set the audio device to HDMI-2.
        batocera-audio set HDMI-2
        # Set the default "auto" audio profile.
        batocera-audio set-profile auto
        # Unmute the audio device.
        batocera-audio setSystemVolume unmute
        # Set audio level to 69.
        batocera-audio setSystemVolume 69
        # Test the audio device with Mallet.wav
        batocera-audio test
        # Toggle the audio mute.
        batocera-audio setSystemVolume mute-toggle

Delay Syncthing until after everything else
# Delay Syncthing until other boot stuff has completed.
if [[ "$1" != "start" ]] && exit 0; then
  if mv /etc/init.d/S27syncthing /etc/init.d/S99syncthing; then
    echo "Successfully delayed Syncthing."
  elif ls /etc/init.d/S99syncthing; then
    echo "Command has already run!"
    exit 0
    echo "Syncthing failed to be delayed."
    touch /userdata/check-boot-custom-sh
    shutdown -h now
    exit 1
exit $?

Play a video on a second screen

Original forum post with a deeper explanation. Artwork needs to be sourced and placed in the appropriate Marquee and roms/Marquee folders first.

Place into system/configs/emulationstation/scripts/game-selected
System=$1 #system name
Romname=${2%.*} #romname
/userdata/ Gameselected $System "$rom"

Place into system/configs/emulationstation/scripts/system-selected
System=$1 #System name
/userdata/ Systemselected $System &

Place in /userdata
case $1 in
if [ -f "/userdata/roms/Marquee/videos/$Romname.mp4" ]
ffmpeg -i /userdata/roms/Marquee/videos/$Romname.mp4 -vf scale=1280:720 -sws_flags bilinear -pix_fmt rgb565le -f fbdev /dev/fb0
if [ -f "/userdata/roms/Marquee/hires/$Romname.jpg" ]
fbv /userdata/roms/Marquee/hires/$Romname.jpg -fer
elif [ -f "$marqueeimage" ]
fbv $marqueeimage -fer
fbv /userdata/roms/mame/images/mame.png -fer
System=$2 #system name
Romname=$3 #romname
if [ -f "/userdata/roms/Marquee/$Romname.png" ]
fbv /userdata/roms/Marquee/$Romname.png -fer
elif [ -f "/userdata/roms/$System/images/$Romname-marquee.png" ]
fbv "/userdata/roms/$System/images/$Romname-marquee.png" -fer
fbv /userdata/roms/Marquee/mame.png -fer
if [ -f "$imagepath.png" ]
fbv "$imagepath.png" -fer
fbv /userdata/roms/mame/images/mame.png -fer

Place in system/scripts
case $1 in
/userdata/ Start $gamepath ${romname%.*} &
killall ffmpeg
  • launch_a_script.txt
  • Last modified: 5 days ago
  • by lbrpdx