2

I am writing a bash script that cycles through a list of files and does something either when the file contains a certain word, or the file was created within the last X seconds. The script works fine with only the first requirement

if grep -q $error $f; then

, but I don't know how to include the "or" statement.

I have tried the following ( I am new to bash so I tried things that may not even make sense ).

FILES=logdir/*.out
OLDTIME=86400
CURTIME=$(date +%s)
error='exit'
for f in $FILES
do
    FILETIME=$(stat $f -c %Y)
    TIMEDIFF=$(expr $CURTIME - $FILETIME)
    if [[ grep -q $error $f ]] || [[$OLDTIME -gt $TIMEDIFF ]] ; then

or

if [[ grep -q $error $f || $OLDTIME -gt $TIMEDIFF ]] ; then

gives me

./script.sh: line 12: conditional binary operator expected
./script.sh: line 12: syntax error near `-q'

and

if [ grep -q $error $f ] || [ $OLDTIME -gt $TIMEDIFF ] ; then

gives me

./script.sh: line 12: [: too many arguments
./script.sh: line 12: [: 1: unary operator expected

How can I have both conditions in the if statement?

Vangi
  • 121
  • 4
  • 1
    You are making the common mistake of assuming that `[` or `[[` is part of the `if` statement's syntax. It's not; you simply say `if grep whatever || [ "$OLDTIME" -gt "$TIMEDIFF" ]; then ...` (though ideally you should use lower case for your private variables). – tripleee Jul 24 '19 at 13:44

1 Answers1

3

It's easier than you think :-)

if /bin/true || /bin/false; then echo hi; fi

prints hi

if /bin/false || /bin/false; then echo hi; fi

prints nothing.

In other words, you don't need the [ or [[ operators. Just execute the commands to return their status and use || to "or" them.

GaryO
  • 5,873
  • 1
  • 36
  • 61