Thursday, July 28, 2022

[SOLVED] Shell script loop with File extension is not working as expected

Issue

I have a shell script which gets all the .zips file from the directory and does some processing. But when there is no file present in the directory the loop should not execute. But somehow the loop is still being executed.

#!/bin/bash

FROM_XML_ZIPS=/Users/Docs_2020/ZIP/XML/*.zip

# files
echo "testing .zip files now"
for f in $FROM_XML_ZIPS;
do
  echo "validating $f"
done

Results in

testing .zip files now
validating /Users/Docs_2020/ZIP/XML/*.zip

Is there something i am missing ?


Solution

you used "globbing" feature.

bash recognize glob patterns(*, ...etc) in unquoted string and then try to find matching files.

if no matching files, it just return same string


add shopt command above globbing line to return null when files not exist

shopt -s nullglob
/Users/Docs_2020/ZIP/XML/*.zip


Answered By - fver1004
Answer Checked By - Marilyn (WPSolving Volunteer)