Problem with Bash Script.

Hi guys!

I'm new to the forum and to the Bash coding scene.

I have the following code

paths[0]=/test/a
paths[1]=/test/b
keywords[0]=\"*car*\"
keywords[1]=\"*food*\"

for file in `find paths[] -type f -ctime -1 -name keywords[] -print 2>/dev/null`
do

   #.... do stuff here for every $file found

done

Basically Im trying to make a script that goes to X amount of [Paths] to check if theres a file with [Keyword] thats been there in the past 24 hours.

I would like to loop my path and keywords inside that "find" command and I dont seem to find a way. Ive tried using ${keyword[0]} and it doesnt work.

Any help or any other approach you suggest me will be welcome!

Thanks in advance.

It's certainly not going to work if you force the string to contain quotes. It will search for files with literal quotes in their names.

Also, just repeating the list won't work either. You need -name a -o -name b -o -name c, etc.

Paths can be used as-is, since find takes a literal list there.

You don't even need arrays here. The shell is perfectly capable of splitting strings at need.

So I'd just assemble a list in the $1, $2, ... variables and use it. Then you can pretty much just find "$@"

#!/bin/sh
paths="/test/a /test/b"
keywords="*car* *food*"

set -f # prevent *car* from globbing here
for X in $keywords
do
        if [ -z "$1" ]
        then
                set -- -name "$X"
        else
                set -- "$@" -o -name "$X"
        fi
done

echo find $paths -type f -ctime 1 '(' "$@" ')'
$ ./findl.sh

find /test/a /test/b -type f -ctime 1 ( -name *car* -o -name *food* )

$

It works in any and every bourne shell I have since it doesn't use arrays.

1 Like

Also, don't put the results of the find in backticks there. Do

find ... | while read LINE
do
        echo "line is $LINE"
done

Since that's not prone to bad splitting or too-many-arguments.

1 Like

Worked like a charm without errors!!

Thanks a lot for your help! Learned a lot with this example!

You'll see me around a lot, I'm starting to deal with this at work and I've never done this before.

Hi Corona!
I'm trying to reuse this part of the code but I would like to make sure I understand it first.

I have doubts with the following lines:

if [ -z "$1" ]
  • What does the -z means in here?
set -- "$@" -o -name "$X"
  • Basically you are assigning $@ everything inside $X?

Thanks in advance

Wouldn't the wildcards around filenames need to be escaped?
Wouldn't ctime's parameter need a '-' sign so find searches <= 24 hrs, not = 24hrs?