我正在编写一个脚本,将文件(例如Dropbox Camera Uploads)移动到年份命名的文件夹,如下所示:
#!/bin/bash
#
# Separate (camera) images on directory
# to year named folders.
#
# All files must be named as "yyyy-mm-dd HH:MM:SS.ext"
#
for img in *.{jpg,jpeg,png}; do
year=${img:0:4}
[ -d "$year" ] || mkdir "$year"
mv -iv "$img" "$year/"
done
该脚本按预期方式处理 matchin 文件,但当没有任何具有扩展名的文件时,将扩展到 *.ex
(前两个扩展名字符)。然后它创建空目录,如下所示:
'*.jp'
'*.jp'
'*.pn'
如何忽略没有匹配的文件?
您需要nullglob
选项;与任何内容都不匹配的模式将被忽略,而不是按字面意思处理。
shopt -s nullglob
for f in *.does_not_exist; do
echo "This won't be reached"
done
您有两个主要选项。 正如@chepner所建议的那样,一种是打开nullglob
,这使得无与伦比的 glob 扩展到空:
shopt -s nullglob
另一种是在对文件执行任何操作之前测试文件是否存在:
for img in *.{jpg,jpeg,png}; do
if [ -f "$img" ]; then # not true for '*.jpg' etc
year=${img:0:4}
[ -d "$year" ] || mkdir "$year"
mv -iv "$img" "$year/"
fi
done
您也可以使用 mkdir -p
并跳过-d
测试。
您可以先检查文件是否存在,如果没有,则continue
循环
#!/bin/bash
#
# Separate (camera) images on directory
# to year named folders.
#
# All files must be named as "yyyy-mm-dd HH:MM:SS.ext"
#
for img in *.{jpg,jpeg,png}; do
[ ! -f "$img" ] && continue
year=${img:0:4}
[ -d "$year" ] || mkdir "$year"
mv -iv "$img" "$year/"
done