我目前正在编写一个脚本,它将在X天后使用find命令删除一个文件。
当使用下面的命令时,它会工作,并成功地删除任何超过10天的文件。
find /path/to/file/to/delete -type f -mtime +10 -exec rm -f {} \;但是,当尝试使用以下命令将其作为脚本参数传递时:
./删除-旧文件. 10 10
find /path/to/file/to/delete -type f -mtime +$1 -exec rm -f {} \;我遇到了这个错误:
find: invalid argument `+' to `-mtime'我是否应该用某种方式包装这个变量,以确保它不会妨碍-mtime参数?
发布于 2020-06-04 17:13:06
在您的脚本中,运行带有参数的delete-old- $1 (),否则本地$1将保持为空,因为它与脚本的全局$1不同。
./delete-old-files.sh 10 为了更好地理解本例中的内容,全局$1作为参数传递给本地$2。您可以看到不同的本地$1是路径,但是全局$1是mtime。
#!/bin/bash
delete-old-files() {
local folder
# just some tests to make sure find will run on folder and mtime is set
[ "$2" ] && [ -e "$1" ] && folder="$(realpath "$1")"
[ -d "$folder" ] || return 1
find "$folder" -maxdepth 1 -type f -mtime +$2 -print #-delete
return $?
}
delete-old-files /path/to/file/to/delete $1 || exit $?:如果不想硬编码path,也可以从参数中阅读。您可以遍历位置参数,将mtime读入var并删除所有不是有效路径的内容。
(参见此answer)
用剩余的参数调用find (将处理非平凡的文件夹名称)
# script
find "$@" -maxdepth 1 -type f -mtime +$days -print #-delete使用任意数量的文件夹运行脚本(没有函数)
./delete-old-files.sh ~/dir1 "path/to/dir 2" 10https://stackoverflow.com/questions/62197943
复制相似问题