bash - How to handle no matching files when using ${f%.gz} syntax -


i'm developing script process , move away compressed files dropped folder.

the script works long gets dropped folder compressed file. however, if script executes when there no compressed files process bash function ${f%.gz} gives unexpected results.

here script, example of problem case afterwards:

files="$ingest_dir/*.gz"  f in $files     justfilename=${f##/*/}     syslog -s -l n "archiving \"$justfilename\""     unzippedpath=${f%.gz}     syslog -s -l n "moving \"$unzippedpath\""     unzippedname=${unzippedpath##/*/}     syslog -s -l n "    \"asr_dir/$unzippedname\""     syslog -s -l n "gunzip-ing $f"     gunzip $f     mv "$unzippedpath" "$asr_dir/$unzippedname" done 

again, works if there's @ least 1 .gz file in target directory.

if there aren't .gz, there other files in directory (which must there other reasons) $files contains expanded $ingest_dir plus /*.gz, this:

ingest_dir=/path/to/foo files="$ingest_dir/*.gz" echo $files 

will show

/path/to/foo/*.gz 

that isn't bad except

for f in $files     unzippedpath=${f%.gz}     echo $unzippedpath done 

yields

somefile.txt someotherfile.exe yetsomeotherfile.dat 

so there elegant way not iterate if there no such compressed files handle? script working because learned ${f##/*/} , ${f%.gz} this question & answer, i'm thinking there might better way than

files="$ingest_dir/*.gz" 

to start things off... or right away before heading loop.

if you're using bash set nullglob before loop:

shopt -s nullglob f in $files 

---- add ----

another way using while read , process substitution:

while ifs= read -r f;     ... done < <(command) 

where command use of find or compgen, find more specific files:

find -type f -name '*.gz' compgen -g '*.gz' 

if we're reading input within loop, use other fds when opening file:

while ifs= read -ru 4 f;     ... done 4< <(command) 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -