Shell script: foreach file -> targzip

Hi there,

I need some help with a shell script (I'm no sh script expert, but I hope this will explain how I want my script):

dir = /home/user/files/
foreach(*.jpg file in $dir) {
    tar -cf $file(-.jpg).tar $file;gzip $file(-.jpg).tar
}
mv -f $dir*tar.gz /home/user/pictures/

Thanks for any help. :slight_smile:

Something like

#!/bin/bash
DIR=/home/user/files
for FILE in $DIR/*.jpg
do
    F=${FILE%.jpg}
    tar -cf $F.tar $FILE
    gzip $F.tar
    mv -f $DIR/$F.tar.gz /home/user/pictures/
done

Thanks for the reply, but would this script only work for *.jpg files? <3

:eek: It didn't but i've corrected it so it does. :slight_smile:

1 Like

Hmm,

if it's no .jpg files in the files, it makes two files:
.tar
.tar.gz

Is it possible to run the for - only if there are any .jpg files in the dir?

Thanks.

Try adding this between DIR= and for:

ls $DIR/*.jpg >/dev/null 2>&1
if [ $? == 0 ]; then

and append following to the end of your script:

else
echo "No jpg files in $DIR"
fi
1 Like

Thanks guys!

I found another 'bug'. I only want the jpg file to be packed, not

home
	user
		files
			image.jpg

Excuse me for asking, but what is the point of putting a single .jpg file into a tar archive? Als why gzip this archive that only contains this one, already compressed file (.jpg) ?

Hehe, it's actually not jpg files, it was just an example.

Anyone?
I guess I have to cd $DIR first, but I'm not sure.

Just cd to the directory first and then tar without the pathnames. Alternatively, as there is no advantage to putting a single file into a tar archive, you might also just gzip the file without tar.

Like this?

#!/bin/bash
DIR=/home/user/files
cd $DIR
ls *.jpg >/dev/null 2>&1
if [ $? == 0 ]; then
for FILE in *.jpg
do
    F=${FILE%.jpg}
    tar -cf $F.tar $FILE
    gzip $F.tar
    mv -f $F.tar.gz /home/user/pictures/
done
else
echo "No jpg files in $DIR"
fi

Looks fine to me. If you put double quotes around variable references it will also work for files that have spaces in their names..