Post your handy utility scripts!

Imagine using YouTube to watch YouTube videos in the current year!

I use this script to watch videos:

#!/bin/sh
# ytp - a simple script that downloads and plays a video!
# No buffering, no telemetry, no ads, and you get to keep the video locally

# Modify these variables as needed:
# Directory for downloaded videos:
DIR="$HOME/Videos/temp"
# Video player:
PLAYER="xdg-open"
#PLAYER="/usr/bin/smplayer"

# Downloader and options:
YTDL="/usr/bin/yt-dlp"
YTDLOPTS="--no-playlist"
YTDIROPTS="-P \"$DIR\""

set -e

# Get URL from clipboard if run without argument:
if [ -z "$1" ]; then
  URL="$(xclip -o -sel c)"
else
  URL="$1"
fi

# Get video filename
printf "[URL]: %s\n" "$URL"
FILENAME=$("$YTDL" "--get-filename" "$YTDIROPTS" "$URL")
printf "[FILE]: %s\n" "$FILENAME"

# Download video
printf "[CMD]: \"%s\" \"%s\" \"%s\" \"%s\"\n" "$YTDL" "$YTDLOPTS" "$YTDIROPTS" "$URL"
"$YTDL" "$YTDLOPTS" "$YTDIROPTS" "$URL"

# Play video
printf "[CMD]: \"%s\" \"%s\" >/dev/null 2>&1\n" "$PLAYER" "$FILENAME"
"$PLAYER" "$FILENAME" >/dev/null 2>&1

There are two ways to use it, either with a video URL, like this:

ytp https://www.youtube.com/watch\?v\=vyR2NWYn6hE

in which case, if you use Zsh, check out my post on bracketed paste magic.

Alternatively, if you have the URL already in the clipboard, it’s sufficient to just write:

ytp

and the script will use the URL from your clipboard. There is no error checking, however, so be careful what you have in your clipboard.

Of course, this is only usable if you have a very fast connection, or a very slow one, because it doesn’t stream the video, but downloads it in its entirety before playing it. For me, this is preferable in 99% of times, unless the video is really large, in which case it takes ages to download it. If you want to stream the video, any media player worth its salt will open a video URL.

Also, remember to clean your downloaded videos directory from time to time, unless you have plenty of storage space.

3 Likes