Help with Bash Script - Intermittent Exits and Filename Formatting

December 18, 2025 4 answers
Asked by ~+coastal erosion!
I'm having some trouble with my Bash script that processes YouTube URLs. At times, the script exits after just the first line without running the remaining commands, which is really confusing. Here's what I have: ```bash #!/bin/bash yt-dlp --skip-download --flat-playlist --print-to-file id 'ids.txt' $1 awk '!seen[$0]++' ids.txt | tee ids.txt awk '{print NR, $0 }' ids.txt | sort -rn | awk '{print $2}' > ids.log awk '{print "wget `http://img.youtube.com/vi/"$1"/mqdefault.jpg` -O "NR".jpg"}' ids.log ``` The first command takes a YouTube video or channel URL as the argument and downloads the video IDs. Sometimes it works and other times it doesn't. The second command removes duplicates from the list of IDs, while the third sorts them in reverse order. Finally, the fourth command generates a wget command to download the thumbnail images. I would love some help troubleshooting why it exits unexpectedly. Additionally, I'd like to enhance the script by formatting the output filenames with padding (e.g., turning 1.jpg into 00001.jpg). Thanks in advance for any advice!

Answers

Dabbler
It could be a malformed URL issue. Generally, YouTube URLs are quite stable, but itโ€™s worth checking. You might want to simplify your commands too. Instead of a long line of awk, consider using a bash pipeline directly. Also, you can filter duplicates with `sort -u` or `sort -ur` for reverse order. Good luck!
Reply to this answer
_corner_kick
Definitely consider using `-- "$1"` to prevent any issues with options. Just check if your input doesn't start with a `-`, which might confuse the command. That should help keep things running smoothly.

~+coastal erosion!: Thanks! Iโ€™ll try that out.

Reply to this answer
!adjust the tripod
For the file naming, you can use the command `printf "%05d" $output` to add the zeros for padding. This way, your output filenames will have the format you need.
Reply to this answer
Q7 fixedpt
It's likely that special characters in the URL are breaking the command mid-process. You should put the URL in double quotes like this: "$1". This could help avoid those intermittent exits you're experiencing. Give it a shot!
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions