3

I'm trying to create a script that removes my images that are not in DB

There is my code (Updated): I have 1 problems:

  • Problem with the like syntax like '%$f%'
#!/bin/bash

db="intranet_carc_development"
user="benjamin"

for f in public/uploads/files/*
do
  if [[ -f "$f" ]]
  then
    psql $db $user -t -v "ON_ERROR_STOP=1" \
    -c 'select * from public.articles where content like "%'"$(basename "$f")"'%"' | grep . \
    && echo "exist" \
    || echo "doesn't exist"
  fi
done

And I have the following error :

ERROR:  column "%1YOLV3M4-VFb2Hydb0VFMw.png%" does not exist
LINE 1: select * from public.articles where content like "%1YOLV3M4-...
                                                         ^
doesn't exist
ERROR:  column "%wnj8EEd8wuJp4TdUwqrJtA.png%" does not exist
LINE 1: select * from public.articles where content like "%wnj8EEd8w...

EDIT : if i use \'%$f%\' for the like :

/purge_files.sh: line 12: unexpected EOF while looking for matching `"'
./purge_files.sh: line 16: syntax error: unexpected end of file
Jason
  • 2,493
  • 2
  • 27
  • 27
Benjamin Barbé
  • 281
  • 2
  • 4
  • 16

1 Answers1

1

There are several issues with your code :

  • $f is public/uploads/files/FILENAME and i want only the FILENAME

You can use basename to circumvent that, by writing :

f="$(basename "$f")"
psql $db $user -c "select * from public.articles where content like '%$f%'"...

(The extra quotes are here to prevent issues if you have spaces and special characters in your file name)

As shown in the linked questions, you can use the following syntax :

#!/bin/bash

set -o pipefail #needed because of the pipe to grep later on

db="intranet_carc_development"
user="benjamin"

for f in public/uploads/files/*
do
  if [[ -f "$f" ]]
  then
    f="$(basename "$f")"
    psql $db $user -t -v "ON_ERROR_STOP=1" \
    -c "select * from public.articles where content like '%$f%'" | grep . \
    && echo "exist" \
    || echo "doesn't exist"
  fi
done
Aserre
  • 4,916
  • 5
  • 33
  • 56