Grimlockz
Grimlockz

Reputation: 2581

script to compress user files via searching through folders for certain folder name

I'm writing a function for one of my programs that will need to search through a number of folders until we find a folder called "userfiles" then we tar up this folder giving the filename of the folder it was found in. Is the below approach the best way to go?

compress(){
NAME=$(cat $USER_HOME/server.txt | sed -e "s/ //g")
USERS=/var/www/home/user/area/*/*/*/
IDS=${PWD##*/}

# Apache Logs
tar -zcvf logs-$NAME.tar.gz /var/log/apache2

# User Logs
 for i in $USERS; 
       do
               if [ ! -d "userfiles" ];
                       then
                               tar -zcvf userfiles-$NAME-"$IDS".tar.gz  $USERS
               fi
 done;

# Linux Logs
tar -zcvf linux-logs-$NAME.tar.gz /var/log/auth.log* /var/log/syslog* /var/log/kern.log* /var/log/mail.log*


}

Upvotes: 0

Views: 246

Answers (3)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200523

This code:

for i in $USERS; 
  do
    if [ ! -d "userfiles" ];
      then
        tar -zcvf userfiles-$NAME-"$IDS".tar.gz  $USERS
    fi
done;

won't do what you described it should do. Instead, if a folder userfiles does not exist in the current working directory, it will tar all user folders multiple times.

Try something like this:

for d in $USERS; do
  if [ -d "${d}userfiles" ]; then
    tar -zcvf "userfiles-$NAME-$IDS.tar.gz" "${d}userfiles"
  fi
done

Upvotes: 1

Uwe
Uwe

Reputation: 728

There are several things in this script that will not work, and I'm not sure I found them all:

  1. Do you really want to check all directories that are exactly 3 levels below /var/www/home/user/area/? I'd expect either something more restrictive (that is, only within subdirectories that carry certain names) or something more permissive (that is, all directories at most 3 levels below /var/www/home/user/area/).

  2. The for loop uses a variable i, but i isn't used anywhere in the body of the loop. That can't work.

  3. The test if [ ! -d "userfiles" ] is executed always in the same (i.e., the current) directory. That can't work either.

  4. I don't understand the negation in if [ ! -d "userfiles" ].

  5. The argument of tar is $USERS. I'd expect something like "$i/userfiles".

Upvotes: 0

Jens
Jens

Reputation: 72756

I'd save a useless use of cat with

 NAME=$(sed -e "s/ //g" $USER_HOME/server.txt)

It also looks like you never use $USERS and $IDS in the function.

Upvotes: 0

Related Questions