Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through files in directory and zip

Tags:

bash

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?

like image 366
rtho782 Avatar asked Nov 01 '25 11:11

rtho782


2 Answers

You can use so called Parameter expansion, which I believe is a good use for you:

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

More on Parameter Expansion - here

like image 149
Krzysztof W Avatar answered Nov 03 '25 00:11

Krzysztof W


You need to extract filename from the path:

FILES=/media/user/storage/unzipped/*
for f in $FILES
do
  filename=$(basename "$f")
  7za a -t7z /media/user/storage/zipped/${filename}.7z $f -mx9 -r -ppassword -mhe
done
like image 34
Martin Avatar answered Nov 03 '25 02:11

Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!