bashyoutube

Get youtube video title while video downloading


In my bash script I consistently download video:

youtube-dl -f mp4 -o '%(id)s.%(ext)s' --no-warnings $URL

and then getting video title:

TITLE=$(youtube-dl --skip-download --get-title --no-warnings $URL | sed 2d)

Both of these commands take some time: the former takes 1-10 min (depending on video duration), and the latter takes 10-20 seconds.

Is there any way to get video title in background while downloading video?

PS. I can't send to background first command (download video) because after I work with video file: get file size and duration for item meta in rss feed.


Solution

  • Although you could run the second command in background, thus making two requests to YouTube, better would be to do it with a single call to youtube-dl, using the --print-json option, combined with a jq filter:

    title=$(youtube-dl -f mp4 -o '%(id)s.%(ext)s' --print-json --no-warnings "$url" | jq -r .title)
    

    Video will be downloaded in background, and all video details will be printed right away. You can then filter the fields of interest with jq as above, or store them for later use:

    youtube-dl -f mp4 -o '%(id)s.%(ext)s' --print-json --no-warnings "$url" >metadata
    title=$(jq -r ".title" metadata)
    duration=$(jq -r ".duration" metadata)
    view_count=$(jq -r ".view_count" metadata)
    

    In case you wish to have progress output while downloading and store metadata to a JSON file, you'll have to use the --write-info-json option instead. The data will be stored in the file named as your video file, but with extension .info.json. For example:

    youtube-dl -f mp4 -o 'video.%(ext)s' --write-info-json "$url"
    title=$(jq -r ".title" "video.info.json")