Home > Blockchain >  Usage of for loop and if statement in bash
Usage of for loop and if statement in bash

Time:03-24

I want to prepare script to delete all the folders created before 3 months on the EC2 directory. The folders look like this

20220310
20220304
20220210
20220203
20210403
20210405

in this case the last two directories should be deleted

code :

#!/bin/bash
for i in $directory/*;do 

    if [ "$i" == "*202104*" ];then
        echo $i
        rm -rf $i
    fi
done

CodePudding user response:

First I would calculate the date it was 3 months ago with the date command:

# with GNU date (for example on Linux)
mindate=$(date -d -3month  %Y%m%d)

# with BSD date (for example on macOS)
mindate=$(date -v -3m  %Y%m%d)

Then I would use a shell arithmetic comparison for determining the directories to remove:

# for dirpath in "$directory"/*
for dirpath in "$directory"/{20220310,20220304,20220210,20220203,20210403,20210405}
do
    dirname=${dirpath##*/}

    (( dirname <= mindate )) || continue

    echo "$dirpath"
    # rm -rf "$dirpath"
done

CodePudding user response:

== doesn't do wildcard matching. You should do that in the for statement itself.

There's also no need to put * at the beginning of the wildcard, since the year is at the beginning of the directory name, not in the middle.

for i in "$directory"/202104*; do
    if [ -d "$i" ]; then
        echo "$i"
        rm -rf "$i"
    fi
done

The if statement serves two purposes:

  1. If there are no matching directories, the wildcard expands to itself (unless you set the nullglob option), and you'll try to remove this nonexistent directory.
  2. In case there are matching files rather than directories, they're skipped.

CodePudding user response:

Suggesting to find which are the directories that created before 90 days ago or older, with find command.

 find . -type d -ctime  90

If you want to find which directories created 90 --> 100 days ago.

 find . -type d -ctime -100 -ctime  90

Once you have the correct folders list. Feed it to the rm command.

 rm -rf $(find . -type d -ctime  90)
  •  Tags:  
  • bash
  • Related