1

I am creating bash script and everything works fine except for this:

read -p "Write directory names:" -a dir
for f in /home/user/downloads/${dir[@]}/*.zip; do
    if [ -f $f ]; then
        #do something
    else 
        #do something else
    fi
done

I want to check if .zip file exists inside a directory; for multiple directories one after another.

nekdo
  • 13
  • 2

1 Answers1

2

You can't substitute the array into the filename, you need to loop over the array.

read -p "Write directory names:" -a dirs
for dir in "${dirs[@]}"; do
    for f in "/home/user/downloads/$dir/"*.zip; do
        if [ -f "$f" ]
        then
            # do something
        else
            # do something else
        fi
    done
done

If you just want to test whether a wildcard matches anything in each directory, replace the inner loop with one of the solutions here: Test whether a glob has any matches in bash

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Generally a good answer. That said, there are some assumptions baked in here -- that `nullglob` isn't set, for one. And I'm not sure if the behavior if one of the directories contains multiple zip files (of running the "do something" block multiple times) is intended or not. – Charles Duffy Jan 27 '20 at 21:46
  • @CharlesDuffy Good point. I've added a reference to a question that just shows how to check if any `.zip` files exist in the directory. – Barmar Jan 27 '20 at 21:49