Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to tar folders with spaces

Tags:

bash

tar

I am trying to make a bash script which will tar all folders individually recursively.

However, I have a problem because some folder names have spaces, etc. So it does not work correctly.

What I have:

#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for i in $(ls ./2011)
do
    tar -zcvf "$i".tar.gz "$i"
done
IFS=$SAVEIFS

However problems arise for example:

tar -zcvf St Patricks Day Bar Night.tar.gz St Patricks Day Bar Night

The spaces cause problems, what's a good way around this?

like image 281
Neutralise Avatar asked Oct 15 '25 20:10

Neutralise


1 Answers

Use double quotes around the file name and bash filename expansion instead of ls.

#!/bin/bash
for i in ./*
do
    echo tar -zcvf "$i.tar.gz" "$i"
done
like image 127
Mu Qiao Avatar answered Oct 17 '25 13:10

Mu Qiao



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!