Bash script to tar folders with spaces
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 Pat开发者_运维问答ricks Day Bar Night
The spaces cause problems, what's a good way around this?
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
ls ./2011 | while read i
do
echo tar -zcvf "$i.tar.gz" "$i"
done
What against
#!/bin/bash
ls ./2011 | while read i; do
do
printf "%s***" tar -zcvf "$i.tar.gz" "$i"
done
? Be aware that the printf
stuff serves to see the boundaries between arguments.
The problem is not with your script (although there might be problems with that too -- if nothing else, it is two magnitudes more complex than it needs to be). The problem is that you need to quote the file name with spaces when you invoke the script.
yourscript "St. Patrick's Day Bar Night"
For what it's worth, the ls
in backticks is superfluous; just do for i in ./2011/*
instead. As far as I can tell, the fidgeting with IFS
is merely unnecessary, but it might also be causing problems.
精彩评论