2

My script tars a folder in my /home/user directory and saves it all in a backup folder. However, when I open each of the tar.gz all of them have the directory /home/user and then the folders and files I wanted to compress.

My script:

#!/bin/bash

if [ ! -d ~/backup ]; then
    mkdir ~/backup
fi

for i in `ls ~/folder`; do
    echo "~/folder/$i"
    if [ -d ~/folder/$i ]; then
        tar -zcf ~/backup/$i.tar.gz ~/folder/$i
    fi
done

What can I do to prevent /home/user to be saved?

1 Answer 1

0

You must to go inside to that folder. Something like:

#!/bin/bash

if [ ! -d ~/backup ]; then
    mkdir ~/backup
fi

cd ~/folder

for i in *; do
    echo "~/folder/$i"
    if [ -d "$i" ]; then
        tar -zcf ~/backup/"$i".tar.gz "$i"
    fi
done

Also, is better to use quotes for variables when these variables refers to file names.

2
  • I was looking for a solution that wouldn't have the need to use cd but it seems like it is the only way. Anyway, thanks for your answer because I also had the issue with the spaces and this way fixes my problem.
    – dabadaba
    Apr 6, 2014 at 10:17
  • 1
    There is nothing wrong to use cd. After the for loop you can go back to the old directory if you need using cd $OLDPWD. Apr 6, 2014 at 10:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .