我正在尝试创建一个删除不在DB中的图像的脚本
我的代码(已更新): 我有一个问题:
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
我有以下错误:
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...
编辑:如果我对\'%$f%\'
使用like
:
/purge_files.sh: line 12: unexpected EOF while looking for matching `"'
./purge_files.sh: line 16: syntax error: unexpected end of file
答案 0 :(得分:1)
您的代码存在以下问题:
您可以使用basename
来规避:
f="$(basename "$f")"
psql $db $user -c "select * from public.articles where content like '%$f%'"...
(如果你的文件名中有空格和特殊字符,这里的额外引号可以防止出现问题)
您的psql请求将始终返回true even if no rows are found
即使请求失败,您的psql命令也会返回true,除非您set the variable 'ON_ERROR_STOP' to 1
如链接问题所示,您可以使用以下语法:
#!/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