rtho782 rtho782 - 3 months ago 34
Linux Question

Bash loop through files in directory and zip

I am trying to make a bash script to loop through all files in a directory, and individually zip them to another directory.

Currently I have this:

FILES=/media/user/storage/unzipped/*
for f in $FILES
do
7za a -t7z /media/user/storage/zipped/$f.7z $f -mx9 -r -ppassword -mhe
done


The problem is that the variable $f includes the absolute path to the source file, so my output file ends up in /media/user/storage/zipped/media/user/storage/unzipped/

How can I extract only the name from the $f variable?

Answer

You can use basename function:

FILES=/media/user/storage/unzipped/*
for f in $FILES
do
  7za a -t7z "/media/user/storage/zipped/$(basename $f).7z" $f -mx9 -r -ppassword -mhe
done

But, you may have problem with files in subfolders, so you can change the wordking directory:

#record current dir
OWD=$(pwd)  

# move to interesting directory 
cd /media/user/storage/unzipped

# zip
for f in *
do
  7za a -t7z /media/user/storage/zipped/$f.7z $f -mx9 -r -ppassword -mhe
done

# restore dir
cd $OWD
Comments