Thoughts on Tech

Youtube from the Command Line

This project is a script that allows you to search Youtube from the command line with certain parameters. It is possible to view Youtube as simply a library of videos that you can access however you want. I did this on Linux Mint DE, but it will work on any distribution.

The script is as follows:

#!/bin/bash

# Default values
QUERY=""
LIMIT=10
EXCLUDES=()
MIN_DURATION=""
PRINT_FMT="%(title)s | %(webpage_url)s"

# Parse arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        --query|-q)
            QUERY="$2"
            shift 2
            ;;
        --limit|-n)
            LIMIT="$2"
            shift 2
            ;;
        --exclude|-x)
            EXCLUDES+=("$2")
            shift 2
            ;;
        --min-duration|-d)
            MIN_DURATION="$2"
            shift 2
            ;;
        *)
            QUERY="$QUERY $1"
            shift
            ;;
    esac
done

QUERY=$(echo "$QUERY" | sed 's/^ *//;s/ *$//')

if [[ -z "$QUERY" ]]; then
    echo "Usage: ytsearch --query \"search terms\" [--exclude channel] [--min-duration seconds] [--limit N]"
    exit 1
fi

# Build match-filter expression
FILTER=""
for CH in "${EXCLUDES[@]}"; do
    FILTER="$FILTER & channel != '$CH'"
done

if [[ -n "$MIN_DURATION" ]]; then
    FILTER="$FILTER & duration > $MIN_DURATION"
fi

FILTER="${FILTER# & }"

# Build base command
CMD=(yt-dlp "ytsearch${LIMIT}:${QUERY}" --quiet --no-warnings --print "$PRINT_FMT")

# Only add match-filter if it's non-empty
if [[ -n "$FILTER" ]]; then
    CMD+=(--match-filter "$FILTER")
fi

# Run it
"${CMD[@]}"

Paste it into an appropriately named file — I called it ytsearch — and save it in the bin folder/directory; this will mean you can run it from anywhere. Don't forget to make it executable by running the following command: chmod +x ytsearch. With this done, you can run it from the command line as follows: