Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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.

share|improve this answer
    
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 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. –  Radu Rădeanu Apr 6 at 10:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.