fswatch="/usr/local/bin/fswatch"
downloads_dir="/Users/yourname/Downloads"
vault_dir="/Users/yourname/Data/我的笔记"
folder_dir=""
manual='yes'
pid=$(pgrep -f fswatch)
if [ -n "$pid" ]; then
echo "已在运行,请不要重复启动!"
exit 1
fi
$fswatch -x --event Created "$downloads_dir" | while read line; do
file=$(echo "$line" | awk -F ' Created' '{print $1}')
if [[ "$file" =~ \.md$ ]]; then
target_dir=""
if [ "$manual" == "yes" ]; then
result=$(find "$vault_dir" -not -path '*/\.*' -type d -exec printf "%s/\n" {} + | sed "s|^$vault_dir||")
result=$(echo $result)
IFS=' ' read -ra options <<< "$result"
escaped_options=$(IFS=','; echo "${options[*]}" | sed 's/,/","/g;s/^/"/;s/$/"/')
read -r selectedOption < <(osascript -e "
tell application \"System Events\"
activate
set userChoice to choose from list (${escaped_options}) with title \"请选择目标文件夹\" with prompt \"请选择:\"
return userChoice as text
end tell
")
if [ "$selectedOption" == "false" ]; then
echo "用户放弃了文件移动"
else
target_dir="${vault_dir}${selectedOption}"
fi
else
target_dir="$vault_dir/$folder_dir"
fi
if [ "$target_dir" != "" ]; then
if [ ! -d "$target_dir" ]; then
echo "${target_dir}不存在!"
osascript -e "display alert \"${target_dir}不存在!\" buttons {\"好的\"} default button 1"
continue
fi
filename=$(echo "$file" | awk -F '/' '{print $NF}')
if [ -f "$target_dir/$filename" ]; then
ext=$(echo "$filename" | cut -d'.' -f2)
filenameonly=$(echo "$filename" | cut -d'.' -f1)
current_date=$(date +%Y%m%d%H%M%S)
random_number=$(( (RANDOM % 1000) + 1 ))
echo "文件{$filename}改名成了$filenameonly-副本-$current_date-$random_number.$ext"
mv "$file" "$target_dir/$filenameonly-副本-$current_date-$random_number.$ext"
else
mv "$file" "$target_dir/"
fi
echo "$filename 已保存成功!"
osascript -e "display notification \"$filename 已保存成功!\" with title \"提示:\""
fi
fi
done