Bash Clean Files

1 minute read

Description

So a team member came with the following problem:

A server was executing the following bash commands to clean files in a directory: cd /mnt/c/scripts/backups/; ls -l; find . -name \*.dat* -mtime +31 -exec ls -l {} \;; find . -name \*.dat* -mtime +31 -exec rm {} \;

The issue was that for some scripts worked but for others, bash was dropping into a directory it wasn’t supposed to and deleting files there.

To Resolve:

  1. Proposed solution:

    1
    
    dir="/mnt/c/scripts/backups"; if [ -d "$dir" -a ! -h "$dir" ]; then ls -l; find . -name \*.dat* -mtime +31 -exec ls -l {} \;; find . -name \*.dat* -mtime +31 -exec rm {} \; else :; fi
    
  2. I first tried various things like:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    #!/bin/bash
    
    cd /mnt/c/scripts2
    RESULT=$?
    if [ $RESULT -eq 0 ]; then
    echo "success"
    else
    echo "failed"
    fi
    
    1
    2
    3
    4
    5
    6
    7
    8
    
    dir="/mnt/c/scripts2"
    if [ -d "$dir" -a ! -h "$dir" ]
    then
       echo "$dir found"
       cd /mnt/c/scripts
    else
       :
    fi
    
    • This worked as expected. I would get success for valid directories and failed for non-valid. But I wanted it to “do nothing”, so I used : instead.

    • And then tried to make them one liners:

    1
    2
    3
    4
    
    dir="/mnt/c/scripts2"; if [ -d "$dir" -a ! -h "$dir" ]; then echo "$dir found"; cd /mnt/c/scripts; else :; fi
    # blank as expected
    dir="/mnt/c/scripts"; if [ -d "$dir" -a ! -h "$dir" ]; then echo "$dir found"; cd /mnt/c/scripts; else :; fi
    # echo line "/mnt/c/scripts found"
    

Comments