Last active
November 6, 2023 09:35
-
-
Save tpu01yzx/c476839b808fd6939f7059efdc9e7e00 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# 设定搜索的目录 | |
SEARCH_DIR="/mnt" | |
BACKUP_DIR="backup" | |
echo "SEARCH_DIR:$SEARCH_DIR" | |
echo "BACKUP_DIR:$BACKUP_DIR" | |
echo "Remove all the files in $SEARCH_DIR except $SEARCH_DIR/$BACKUP_DIR/" | |
find $SEARCH_DIR -mindepth 1 -not -name backup -not -path "$SEARCH_DIR/$BACKUP_DIR/*" -exec rm -rf {} + | |
echo "rsyncing files from $SEARCH_DIR/$BACKUP_DIR/" | |
rsync -avxH --numeric-ids --exclude='var/lock' --exclude='var/run' --exclude='var/lib/pacman' --exclude='var/cache/pacman/pkg' --exclude='tmp' --exclude='dev' --exclude='proc' --exclude='sys' --exclude='run' --exclude='mnt' --exclude='media' --exclude='lost+found' "$SEARCH_DIR/$BACKUP_DIR/" /mnt/ | |
# 使用 find 命令查找所有大小不超过 2048 字节的文件,但忽略 backup 子目录 | |
# -readable 确保文件是可读的,防止处理无法访问的文件 | |
find "$SEARCH_DIR" -type d -name "$BACKUP_DIR" -prune -o -type f -size -2048c -readable -print | while IFS= read -r file; do | |
# 使用 file 命令检查文件是否为文本 | |
if file -- "$file" | tr -d '\0' | grep -qE 'text|ASCII'; then | |
# 计算文件行数 | |
line_count=$(wc -l < "$file") | |
byte_count=$(wc -m < "$file") | |
# 如果文件只有一行 | |
if [ "$line_count" -eq 1 -a "$byte_count" -gt 2 ]; then | |
echo "found text link file: $file" | |
# 读取文件内容,并去除行尾的非字母数字字符 | |
content=$(sed -r 's/[^a-zA-Z0-9]?$//' "$file") | |
# 判断路径是绝对路径还是相对路径 | |
if [[ "$content" == /* ]]; then | |
# 是绝对路径,将根目录 '/' 替换为 SEARCH_DIR | |
target_path="${SEARCH_DIR}${content}" | |
else | |
# 是相对路径,基于文本文件所在的目录进行解析 | |
target_path="$(dirname "$file")/$content" | |
fi | |
echo "\t target: $target_path" | |
# 确定目标路径是否存在 | |
if [ -e "$target_path" ]; then | |
# 删除文本文件 | |
rm -- "$file" | |
# 创建符号链接,链接名为文本文件的名字 | |
# 链接实际指向原始的路径内容,不管它是绝对的还是相对的 | |
echo "\tln -s -- $content ${file%.*}" | |
ln -s -- "$content" "${file%.*}" | |
fi | |
fi | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment