A Screen Recorder in One Bash Script

A Screen Recorder in One Bash Script

Leader ●2 ●4 ●22
calendar_today ago • schedule4 min read

From My ~/bin, Part 2

rec-gui records my whole screen with sound, and nothing else. There are no scenes, sources or settings panels, just Record and Stop. It's one bash script of 84 lines, and ffmpeg does the actual recording.

You can use it two ways:

  • With a window: run rec-gui and a small window appears with a Record button. While it records, a little timer shows in the corner with a Stop button.
  • With no window at all: run rec-gui --now and recording starts at once, so nothing of the tool ends up in the video. Run rec-gui again to stop.

Either way, the recording is saved in your home folder as video1.mkv, video2.mkv and so on. It never overwrites an earlier file.


Why not OBS?

OBS is excellent, but most of the time I just want "record what's on the screen and what I hear." That shouldn't need a setup screen. ffmpeg can already do it in one command, and the script adds only the parts that make it pleasant to use every day.

The code: rec-gui

#!/bin/bash
# rec-gui - record the screen with sound, nothing else
#
#   Record   starts recording the whole screen + whatever you hear
#   Stop     ends it; the file is saved in your home folder as video1.mkv,
#            video2.mkv, ... (never overwrites an earlier one)
#
# Tip: run `rec-gui` a second time while recording to stop it - handy
# for a keyboard shortcut, so no window needs to sit on your screen.
# `rec-gui --now` records at once with no windows at all (so nothing of the
# tool ends up in the picture); run `rec-gui` again to stop. Prints the file.
# Audio is always the current default output (@DEFAULT_MONITOR@), so it
# follows your headphones. Video is H.264, audio is lossless FLAC.

# Larger text in the yad windows only (not in ffmpeg etc.)
yad() { GDK_DPI_SCALE=1.3 command yad "$@"; }

pidfile="${XDG_RUNTIME_DIR:-/tmp}/rec-gui.pid"

# Already recording? Then this run is the "stop" request.
if [ -f "$pidfile" ] && kill -0 "$(cat "$pidfile")" 2>/dev/null; then
    kill -INT "$(cat "$pidfile")"
    exit 0
fi

now=0; [ "$1" = --now ] && now=1

tmp=$(mktemp -d)
trap 'rm -rf "$tmp" "$pidfile"' EXIT

while true; do
    if [ $now = 0 ]; then
        yad --center --title="Record" --width=300 --text="Record the screen with sound." \
            --button="Record:0" --button="Close:1" || break
    fi

    n=1
    while [ -e "$HOME/video$n.mkv" ]; do n=$((n + 1)); done
    out="$HOME/video$n.mkv"
    size=$(xdpyinfo | awk '/dimensions:/ {print $2}')

    # Players hold the picture back to match their output's delay, but we hear
    # the sound before that delay - so push the recorded sound later to match.
    case $(pactl get-default-sink) in
        bluez_*) delay=0.26 ;;    # Bluetooth headphones
        *)       delay=0.145 ;;   # wired / speaker
    esac

    ffmpeg -nostdin -y \
        -use_wallclock_as_timestamps 1 -thread_queue_size 1024 -f x11grab -framerate 30 -video_size "$size" -i "$DISPLAY" \
        -use_wallclock_as_timestamps 1 -itsoffset "$delay" -thread_queue_size 1024 -f pulse -i @DEFAULT_MONITOR@ \
        -c:v libx264 -preset veryfast -crf 18 -pix_fmt yuv420p \
        -c:a flac "$out" >/dev/null 2>"$tmp/err" &
    rec=$!
    echo $rec > "$pidfile"

    start=$SECONDS
    if [ $now = 1 ]; then
        wait $rec
    else
    ( while kill -0 $rec 2>/dev/null; do
          t=$((SECONDS - start))
          printf '#Recording...  %02d:%02d\n' $((t / 60)) $((t % 60))
          sleep 1
      done; echo 100 ) |
        yad --progress --pulsate --auto-close --posx=20 --posy=20 --width=300 \
            --title="Recording" --text="Recording screen + sound" \
            --button="Stop:0" 2>/dev/null
    fi

    # Stop pressed (or window closed): finish the file properly.
    kill -INT $rec 2>/dev/null
    wait $rec
    rm -f "$pidfile"

    if [ -s "$out" ]; then
        notify-send "Recording saved" "$out" 2>/dev/null
        [ $now = 1 ] && echo "$out"
    else
        yad --error --center --title="Record" --text="Recording failed:\n$(tail -n 5 "$tmp/err")" --button=OK:0
        rm -f "$out"
    fi
    [ $now = 1 ] && break
done

How it works

ffmpeg records two inputs at once. x11grab captures the screen, at whatever size xdpyinfo reports. pulse with @DEFAULT_MONITOR@ captures what you hear, not the microphone. "Default" means it follows whatever output is active, so switching to headphones doesn't break it. Video is H.264 and audio is lossless FLAC, in an MKV file.

Run it again to stop it. When recording starts, ffmpeg's process ID goes into a small file (a pidfile) in $XDG_RUNTIME_DIR. Every run checks that file first. If a recording is already going, this run's only job is to stop it. That makes one keyboard shortcut a start/stop toggle, with no window needed.

Stop it gently. The script stops ffmpeg with kill -INT, the same signal as pressing Ctrl+C. ffmpeg treats that as "finish up": it writes out the last frames and closes the file properly, so the video isn't cut off or damaged.

A fix for sound that runs ahead of the picture. On my laptop, recordings came out with the sound slightly ahead of the video, and more so with Bluetooth headphones. The script checks the current output with pactl get-default-sink. Bluetooth outputs have names starting with bluez_, so those get a bigger correction. -itsoffset then shifts the sound later: 0.26 seconds for Bluetooth, 0.145 seconds for wired. These numbers suit my hardware; if your sound is out of step, these are the two values to adjust.

Timestamps from the clock. -use_wallclock_as_timestamps 1 stamps both inputs with the real time, so the sound and picture line up from the start. -thread_queue_size 1024 gives ffmpeg room to buffer, so a busy moment doesn't drop frames.

Small touches.

  • The file name loop counts up until it finds a free name, so nothing is overwritten.
  • notify-send shows a desktop notification with the file name when the recording is saved.
  • If ffmpeg fails, the last lines of its error output appear in a dialog instead of disappearing.
  • A trap removes the temporary folder and the pidfile on exit, so a crash doesn't leave the next run thinking a recording is still going.
  • The yad() function makes the windows' text 30% larger without changing anything else.

One limit: x11grab needs an X11 session. On Wayland, screen capture goes through a different route, so this script won't work there as written.


84 lines, one dependency doing the heavy lifting, and the whole tool fits on one screen. That's what I like about bash: ffmpeg does the hard part, and the script just makes it convenient.

Ben Santora - December 2026

Want more #linux & #bash deep dives?

Join 6,142+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

More Posts

The cleanup failed on the night there was nothing to clean

BashSnippets - Dec 2

A Textile Mill's Dyehouse Ramp Curve: Get One Step Wrong and the Sheet Belongs to the Master

aiomniu - Oct 18

A deploy guard that passes with no token

BashSnippets - Nov 24

My hung process had no file open. It was stuck inside open().

BashSnippets - Dec 1

I Wrote a Script to Fix Audible's Unreadable PDF Filenames

snapsynapseverified - Apr 20
chevron_left
1.2k Points • 28 Badges
Montserrat MA • xiralinux.pages.dev
5Posts
21Comments
10Connections
Linux and AI Advocate - Creator of xiralinux - a lightweight Debian 12 + Openbox live distro built t... Show more

Related Jobs

View all jobs →

Commenters (This Week)

4 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!