Bash清除脚本

时间:2018-06-01 08:46:01

标签: sql bash postgresql psql

我正在尝试创建一个删除不在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

1 个答案:

答案 0 :(得分:1)

您的代码存在以下问题:

  • $ f是public / uploads / files / FILENAME,我只想要FILENAME

您可以使用basename来规避:

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

(如果你的文件名中有空格和特殊字符,这里的额外引号可以防止出现问题)

如链接问题所示,您可以使用以下语法:

#!/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