Querying YouTube From a Terminal

I prefer to stay in a terminal when possible, depending on the task I can often get places quicker. When I realised YouTube offered an RSS feed to each individual channel, I immediately saw the opportunity to put it in a terminal-based RSS reader (I use newsboat - there are others). I realised a problem, however: I didn't actually have any means of querying YouTube, if I didn't know exactly what I was looking for.

The first thing I did, rather than reinvent the wheel, was to look to see what else others had done. But what I saw wouldn't fit my needs. Many of them didn't work OOTB. The few that did work packaged things like their own video player, when I already had mpv: I only wanted the ability to query, then pass that to my video player of choice.

So I Wrote My Own

Eventually I had to concede. It doesn't have a 'proper' name, it has been named 'ytsearch'. It's messy and horrible, it's written in Bash, and it has 'evolved' over time without any planning. Critically however, it actually works, and it packages no extras: it's only a script and runs purely in a terminal. The script fetches and formats the result from a query on an Invidious instance of choice, and plays it from YouTube.

You can select videos, whole playlists, specific items from playlists, or a mixture of the above. When querying, the script returns the duration and first ~50 chars of the video title. When a video is selected, you can stream video and audio; download video and audio; and print URLs or append them to files. The URL is copied to the clipboard for ease of sharing. The config file and command line options allow you to set things such as Invidious instance to use (the script will work as well as the instance you're using - which is why I've made it easy to switch them), number of results to fetch, preferred resolution settings, and query timeout.

Any Unix-like with Bash, coreutils, mpv, and youtube-dl/yt-dlp should be able to run it. xclip is used to copy to the clipboard, but no essential functionality would be lost if this was edited out.

Companion Scripts

'ytformat' just takes links pointing to an Invidious instance, and converts them to a YouTube link, if you are looking to share them as such - fairly straightforward. 'ytchannel' is a bit of a hack: it downloads and deletes a low-quality audio copy of a video, in order to get the YouTube channel it belongs to and to give you the link to its RSS feed, so you can 'subscribe'.

Gimme Gimme

You can get a hold of the scripts here.