Home > other >  Can't run the command 'find' inside script
Can't run the command 'find' inside script

Time:10-12

I have a shell script

IMG_DIR=/hdd/diskS/Foto;

DirScan() {
    for f in $1/*
    do
        fname=${f##*/};
        if [ -d $f ]
        then
            DirScan $f;
        else
            str0="find  "$IMG_DIR" -name '"$fname"' | wc -l ";
            echo $str0;
            res=`$str0`
            echo "res=$res";
            if  [ $res ]
            then
                echo "Remove ";
                #rm $f
            fi;
        fi;
    done;
}

DirScan $1

I have got an error when I run it:

root@zebra:~# ./check_foto /hdd/diskS/2
find /hdd/diskS/Foto -name '35e2fae8bba6d74557bc2fa631fcb51bf1aca650_hq.jpg' | wc -l
find: paths must precede expression: `|'
res=

But at the same time, when I run this command directly, it is working well:

root@zebra:~# find /hdd/diskS/Foto -name '35e2fae8bba6d74557bc2fa631fcb51bf1aca650_hq.jpg' | wc -l
2

I tried to remove part "| wc -l". There is no error in this case, but variable $res is empty, disregard of find returns 2 lines. What am I doing wrong?

CodePudding user response:

Your string is ill-formed - you can't use un-escaped double-quotes within a double-quoted string.

Either you could do something like this:

#...
str0="find \"$IMG_DIR\" -name \"$fname\" | wc -l"
echo $str0
res=$(eval $str0)
#...

or, simply:

#...
res=$(find "$IMG_DIR" -name "$fname" | wc -l)
#...
  • Related