1

I use this code in my scripts to process files inside a folder, but it only works for subfolders.

if [ -d "$1" ]; then for file in "${1%/}/"*/*(*.mkv|*.mp4|*.avi); do 

I know I can just remove /* to work with flat folders, but I'm looking for a more clean way to handle both flat folders ( no subfolders ) and folders with subfolders.

I have big code in the for loop so I don't want solutions that rely on find

2 Answers 2

2

Try globstar and extglob which is specific to bash

#!/usr/bin/env bash shopt -s globstar extglob if [[ -d $1 ]]; then for file in "$1"/**/*.@(mkv|mp4|avi); do : done fi 
8
  • extglob enable it and use bash Commented Mar 24, 2020 at 6:50
  • try now, the *.@ seems to work, it was *@. that before. Commented Mar 24, 2020 at 6:50
  • Line 9 says fi, how did you get that error message? Commented Mar 24, 2020 at 6:53
  • @Freedo It would work if the website ran your code on a directory with files matching. When you run bash code on some website like that, the code is not actually running on your machine. Your browser just sends the code off, it gets executed, and their web server sends the output back. It would be better if you tested your code on your own machine, in a terminal. Commented Mar 24, 2020 at 7:05
  • Working now, I don't know what happened earlier I changed it to see if it'd work... but anyway thanks!! Brilliant answer. You can delete the old comments Commented Mar 24, 2020 at 7:21
1

I have big code in the for loop so I don't want solutions that rely on find

If you change the for loop to a while loop and use read, it's easy to rely on find without further refactoring of what's inside the loop:

find "$1" -name "*.mkv" -o -name "*.mp4" -o -name "*.avi" -print0 | \ while read -d '' file; do # Process file done 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.