Home > Software design >  How to delete folders that fail a condition in bash script
How to delete folders that fail a condition in bash script

Time:12-10

I have a number of folders that are constantly and automatically generated. Some are garbage and need to be cleared out. Each folder produces a generations.txt which I want to count the important lines to determine whether or not the folder should be deleted. I'd like to have a bash script I can run every so often to clean things up.

Here's what I have. I can echo the command I want but I don't believe it outputs the integer to compare to 5. Any suggestions would really help me out. Please and thank you!

#!/bin/bash
SEARCHABLES="grep -Evc 'Value:' "

for d in */
do
  PATH=$d'generations.txt'
  COMMAND=$SEARCHABLES$PATH
  if $COMMAND < 5
  then
    rm -rf $d
  fi
done

CodePudding user response:

You're not getting the output of the command, you need $(...) to execute a command and substitute its output.

To perform the arithmetic comparison, you have to put it inside ((...)).

#!/bin/bash
SEARCHABLES="grep -Evc 'Value:' "

for d in */
do
  PATH="$d"'generations.txt'
  COMMAND=$SEARCHABLES$PATH
  if (( $($COMMAND) < 5 ))
  then
    rm -rf "$d"
  fi
done

CodePudding user response:

See BashFAQ/050 - I'm trying to put a command in a variable, but the complex cases always fail! for a more detailed explanation.

In short, embedding a command in a variable is a faulty approach to the problem here because the single quotes in 'Value:' will be treated like literal data to search for. Syntax parsing happens before expansions, so you can't embed quotes in a variable like that. What you need is a function:

_count() {
  grep -Evc 'Value:' "$1"
}
_count "$PATH"

Then compare the output of the function using an arithmetic expression:

occurrences=$( _count "$PATH" )
if (( occurrences < 5 )) ; then
...
fi 
  •  Tags:  
  • bash
  • Related