Help with Loop !!


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Help with Loop !!
# 1  
Old 05-14-2015
Help with Loop !!

[Hi Guys!

This is a very beginner question I think

I am writing a Bash script that aims to perform two tasks. First, find files and see how long it has been created.

If more than 30 days then delete; if less than 30 days, tar.

This is the code :


Code:
days=30

   files=($(find . -type f -name 't*'  -mtime +"$days"))

for   files in ${files[*]};

do

if [[ $? == "0" ]]

then

echo "File is older  than" $days "days"
echo "Deleting files"

rm -rf  $files

fi

if  [[ $? == "1" ]]
then

echo "File is newer  than" $days "days"
echo "Compacting...."
NOW=$(date +"%m-%d-%Y")
FILE="Prime-Backup.$NOW.tar.gz"
tar  -zcf  $FILE $files

fi

done


The proglem I found is. When the code gets to if [[ $? == "0" ]], if it is true, it deletes the file. Ok, thatīs nice.

Therefore, if it is untrue, the code does not goes ahead. It ignores all the rest.

I tried many others possibilities but, I am too stupid to overcome it.

Please, could anybody help me ?

Thanks in advanced.

Last edited by FlavioMiranda; 05-14-2015 at 07:18 PM..
# 2  
Old 05-14-2015
Hi, welcome to the forums.
Please use code tags for code blocks, as requested by (and you have agreed to) the forum rules.

In bash one does set and compare with a single =.
You set a variable when there is no space between the words, but if there is, it is a comparision as you desire.

Just remove one of the ='s.

hth

EDIT:
Also, there is no need to quote numbers.
But it is good practice to quote any and every variable (starting with $) beeing used in a condition. (if you do this, you can 'remove' one of each of the surrounding brackets [])

Last edited by sea; 05-14-2015 at 07:20 PM..
This User Gave Thanks to sea For This Post:
# 3  
Old 05-14-2015
Done...but nothing has change!

Code:
#!/bin/bash

cd /home/pendrive

days=1


   files=($(find . -type f -name 't*'  -mtime +"$days"))

for   files in ${files[*]};

do

if [[ $? = "0" ]]

then

echo "File is older  than" $days "days"
echo "Deleting files"

rm -rf  $files

fi

if  [[ $? = "1" ]]

then

echo "File is newer  than" $days "days"
echo "Compacting...."
NOW=$(date +"%m-%d-%Y")
FILE="Prime-Backup.$NOW.tar.gz"
tar  -zcf  $FILE $files


fi

done

thanks anyway!!
# 4  
Old 05-14-2015
Uhm yes, $? is the exit code of the previously executed command.
You are assigning a list of files fullfilling the condition of beeing older than $days days to a variable having the same name as the array, this may cause conflicts.
Also, there is no point in checking the exit code of the previous command, as it will return always true, within a loop.

In bash, 0 means true, 1 means false.
There is only 1 way to exit with success, but there may be several causes for a failure, so exit code number can be used to identify the cause of the failure.

To conclude, all your files within the array, should be older and therefor could be removed.
The remains could be backed up.

However, i highly recomend to echo your rm command on first attempts, until you are sure the right files are in the array.
Specialy as its enforcing recursive deletion that will not be recoverable!

Also, use quotes around variables, while the array item may handle files using spaces found by find, an unquoted variable will not.

hth
# 5  
Old 05-14-2015
Tried to follow your advises. Not sure if I got it.

Maybe this is not the best way to perform the task.

It is hard to me understand how to treat the false condition.


Code:
#!/bin/bash

cd /home/pendrive

   files=($(find . -type f -name 't*'  -mtime +30))

for   files in ${files[*]}

do

if [[ $? = "0" ]]

then

echo "File is older  than 30 days"
echo "Deleting files"
echo $files
rm -rf  $files
echo "delete"
fi

if  [[ $? = "1" ]]

then

echo "File is newer  than 30 days"
echo "Compacting...."
NOW=$(date +"%m-%d-%Y")
FILE="Prime-Backup.$NOW.tar.gz"
tar  -zcf  $FILE $files


fi

done

# 6  
Old 05-15-2015
Yes there are better ways to do this.

Firstly as you are deleting older files, after this task is complete everything else left will be newer so you could.
find all files older than 30 days and delete
find all files and tar
depending on your OS your find may support delete and you can simply do:

Code:
cd home/pendrive
echo "Deleting old files...."
find . -type f -name 't*' -mtime +30 -delete

echo "Compacting...."
NOW=$(date +"%m-%d-%Y")
FILE="Prime-Backup.$NOW.tar.gz"
find . -type f -name 't*' -print | tar -cz -f "$FILE" --files-from=-

Note: this will create an empty .tar.gz file when no files are found, you may need to get creative to avoid this "feature"
This User Gave Thanks to Chubler_XL For This Post:
# 7  
Old 05-15-2015
If you really want to loop and check the age of files I'd create a reference file that is 30days old and use bash -ot test option to test if file1 is older than file2 eg:

Code:
[ file1 -ot file2 ]

You could do something like this:

Code:
# create temp reference file:
touch -d -30days "/tmp/30dayref.$$"

cd home/pendrive

find . -type f -name 't*' -print | while read file
do
    if [ "$file" -ot "/tmp/30dayref.$$" ]
    then
        #file is old delete it
    else
        #file is younger -- append to archive
    fi
done

# Clean up temp reference file
rm /tmp/30dayref.$$

This User Gave Thanks to Chubler_XL For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

For loop or while loop from a text file

Hi all, i developed a script to measure the uptime of a process in a Solaris 10/11 environments. All is well, but i came across a situation where there are multiple processes of the same name. Basically i have the following result file: beVWARS 13357 19592122 beVWARS 14329 19591910... (4 Replies)
Discussion started by: nms
4 Replies

2. Shell Programming and Scripting

awk loop using array:wish to store array values from loop for use outside loop

Here's my code: awk -F '' 'NR==FNR { if (/time/ && $5>10) A=$2" "$3":"$4":"($5-01) else if (/time/ && $5<01) A=$2" "$3":"$4-01":"(59-$5) else if (/time/ && $5<=10) A=$2" "$3":"$4":0"($5-01) else if (/close/) { B=0 n1=n2; ... (2 Replies)
Discussion started by: klane
2 Replies

3. Shell Programming and Scripting

Reset while loop to loop same file multiple times

Hi, I want to read file multiple times. Right now i am using while loop but that is not working. ex. While read line do while read line2 do echo stmt1 #processing some data based on data., done < file2.txt done < file1.txt # This will have 10... (4 Replies)
Discussion started by: tmalik79
4 Replies

4. Shell Programming and Scripting

Array Variable being Assigned Values in Loop, But Gone when Loop Completes???

Hello All, Maybe I'm Missing something here but I have NOOO idea what the heck is going on with this....? I have a Variable that contains a PATTERN of what I'm considering "Illegal Characters". So what I'm doing is looping through a string containing some of these "Illegal Characters". Now... (5 Replies)
Discussion started by: mrm5102
5 Replies

5. Shell Programming and Scripting

My for loop decides to become an infinite loop?

Hi, I was debating if I should put this in the dummies or scripts section, I apologize in advance if I chose poorly. Fairly new to Unix and BASH scripting but I thought I made it fairly well given my limited understanding. However, the output indicates that it's looping and I'm ending up with a... (5 Replies)
Discussion started by: gotreef
5 Replies

6. Shell Programming and Scripting

S# in a for loop - concatenate $(loop counter)

Hi, hope I am posting in the right section. My problem is that I have 2 or more arguments passed and I want to check if the arguments passed exists or not. The first argument should not exist and the remaining others should exist. example: ./shells.sh argument1 argument2 argument3 ... (5 Replies)
Discussion started by: fight4love
5 Replies

7. Shell Programming and Scripting

BASH loop inside a loop question

Hi all Sorry for the basic question, but i am writing a shell script to get around a slightly flaky binary that ships with one of our servers. This particular utility randomly generates the correct information and could work first time or may work on the 12th or 100th attempt etc !.... (4 Replies)
Discussion started by: rethink
4 Replies

8. Shell Programming and Scripting

Null Handling in Until loop. . .loop won't stop

Hi Im running this script, which is supposed to find the max value build some tables and then stop running once all the tables are built. Thing is , it keeps assigning a null value to $h and then $g is null so it keep building tables i.e. testupdateNUL. How can I stop this? Here is what I have: ... (4 Replies)
Discussion started by: brandono66
4 Replies

9. Shell Programming and Scripting

Using variables created sequentially in a loop while still inside of the loop [bash]

I'm trying to understand if it's possible to create a set of variables that are numbered based on another variable (using eval) in a loop, and then call on it before the loop ends. As an example I've written a script called question (The fist command is to show what is the contents of the... (2 Replies)
Discussion started by: DeCoTwc
2 Replies

10. Shell Programming and Scripting

Is there a better way I could have run this loop. (For loop with two variables)

Sorry for such a dreadful title, but I'm not sure how to be more descriptive. I'm hoping some of the more gurutastic out there can take a look at a solution I came up with to a problem, and advice if there are better ways to have gone about it. To make a long story short around 20K pieces of... (2 Replies)
Discussion started by: DeCoTwc
2 Replies
Login or Register to Ask a Question