Play media from YouTube

query=...; mpv "$(youtube-dl --default-search "ytsearch1:$query" --get-url | tail -n1)"

December 8, 2019MKamnikar

Explanation

youtube-dl --default-search "ytsearch1:$query" --get-url searches for videos on YouTube by the query specified in the query variable at the beginning of the line, printing the URLs of the matches.

| tail -n1 takes the last line of the input.

mpv "$(...)" plays media from the URL printed by the command within $(...), in this example the last item from the YouTube search results.

Limitations

As of 2023-09-03, youtube-dl no longer supports searching on YouTube.

Requires external tools:

  • youtube-dl to search for videos on YouTube
  • mpv to play media from a URL