我在脚本中的“find”命令找不到名称中带有空格的文件和目录

Sim*_*zko 6 command-line bash scripts find

前段时间我写了一个脚本,将超过 3 天的文件和目录从Downloads到移动.Downloads,并在 30 天后从该目录中删除它们。它工作得很好,但仅适用于没有空格的文件。

我调查并发现find我在脚本中使用的命令对于名称中带有空格的任何文件或目录都没有按预期工作。

这是find它的作用:

查找命令输出

我希望看到find命令也能找到带有空格的文件。

这是脚本:

#! /bin/bash
# set -x
export DISPLAY=:0.0

# true - delete, else - move
function process(){
    if [ "$2" = "DELETE" ]; then
        rm -r "$1" && notify-send "$3 $1 deleted!"
    else
    mv "$1" "../.Downloads/$1" && notify-send "$3 $1 moved to ~/.Downloads/$1!"
    fi
}

# remove empty directories
for emptyDir in `find ~/Desktop/ ~/Downloads/ -empty -type d`; do
    notify-send "Directoy $emptyDir was deleted, because was empty!"
done
find ~/Desktop/ ~/Downloads/ -empty -type d -delete

# remove / move old files / directorie
if [ -z "$1" ] || [ "${1,,}" != "delete" ] && [ "${1,,}" != "move" ]; then
    echo "Give as parameter mode ( delete / move )"
    exit
fi

if [ "${1,,}" == "delete" ]; then
    day=30
    path=".Downloads"
    mode="DELETE"
else
    day=2
    path="Downloads"
    mode="MOVE"
  cr  
  if [ ! -d "~/.Downloads" ]; then
    mkdir -p ~/.Downloads
  fi
fi

cd ~/$path

for element in *
do
    if [ -d "$element" ]; then
        if [ $(find "$element" -type f -mtime -$day | wc -l) -eq 0 ]; then
            process "$element" "$mode" "Directory"
        fi
    else
        if [ $(find `pwd` -name "$element" -mtime +$day | wc -l) -gt 0 ]; then
            process "$element" "$mode" "File"
        fi
    fi
done
Run Code Online (Sandbox Code Playgroud)

我恳请您告诉我我可能做错了什么。

提前致谢!

ste*_*ver 13

tl; dr:这不是空格,而是括号1

find命令的-name测试使用 shell glob 表达式 - 在参数周围添加引号可防止 glob 特殊字符被shell解释,但find仍需要对它们进行转义。

前任。

$ touch 'filename with [brackets] in it'
$ find . -name 'filename with [brackets] in it'
$
Run Code Online (Sandbox Code Playgroud)

(没有结果 - 因为[brackets]意味着集合中的任何单个字符b, r, a, c, k, e, t, s);然而

$ find . -name 'filename with \[brackets\] in it'
./filename with [brackets] in it
Run Code Online (Sandbox Code Playgroud)

如果您需要以编程方式实现这一点,您或许可以使用 bash shellprintf添加所需的转义:

$ element='filename with [brackets] in it'
$ find . -name "$(printf '%q' "$element")"
./filename with [brackets] in it
Run Code Online (Sandbox Code Playgroud)
  1. 但是你会在行中遇到空格问题

    for emptyDir in `find ~/Desktop/ ~/Downloads/ -empty -type d`; do
    
    Run Code Online (Sandbox Code Playgroud)

    请参阅为什么循环查找的输出是不好的做法?

  2. 还有许多其他问题,例如引用~[ ! -d "~/.Downloads" ]不会扩展到$HOME- 通常你应该避免~在脚本中