如何实现每次复制/test文件夹时自动递增命名(到test10后重置)?
Solution for Rolling Numbered Folder Copy
Hey there! As someone who’s been in your shoes figuring out file operation automation, let me walk you through the best way to handle this rolling numbered folder copy. Shell scripting is perfect here because it’s lightweight and integrates seamlessly with Unix-like systems (Linux/macOS).
The Core Idea
We’ll write a bash script that:
- Checks if the target directory has existing
/test,/test1, ...,/test10folders - Finds the highest existing number (treating
/testas "0") - Calculates the next name: if the highest is 10, we loop back to
/test; otherwise, increment the number - Runs the copy command to the new target path
The Script
Save this as copy_test.sh (customize the SOURCE and TARGET_DIR variables to match your paths):
#!/bin/bash # Replace with your actual source folder path SOURCE="/test" # Replace with your actual target directory (where the copied folders will live) TARGET_DIR="/path/to/your/target" # Make sure the target directory exists (no error if it's already there) mkdir -p "$TARGET_DIR" # Find all existing test/test1...test10 folders in the target directory existing_dirs=($(ls -d "$TARGET_DIR"/test* 2>/dev/null | grep -E '^'"$TARGET_DIR"'/test([0-9]|10)?$')) # Default to "test" if no existing folders are found next_name="test" if [ ${#existing_dirs[@]} -gt 0 ]; then # Extract numbers from existing folder names (treat "test" as 0) numbers=() for dir in "${existing_dirs[@]}"; do folder_base=$(basename "$dir") if [ "$folder_base" = "test" ]; then numbers+=("0") else # Strip "test" to get the number num=${folder_base#test} numbers+=("$num") fi done # Find the highest number in the list max_num=$(printf "%s\n" "${numbers[@]}" | sort -n | tail -n1) # Calculate next number: loop back to 0 if max is 10, else increment if [ "$max_num" -eq 10 ]; then next_num=0 else next_num=$((max_num + 1)) fi # Generate the next folder name (use "test" instead of "test0") if [ "$next_num" -eq 0 ]; then next_name="test" else next_name="test$next_num" fi fi # Build the full target path TARGET="$TARGET_DIR/$next_name" # Copy the source folder recursively, preserving permissions/timestamps cp -rp "$SOURCE" "$TARGET" echo "✅ Copied $SOURCE successfully to $TARGET"
How to Use
- Open a text editor and paste the script above
- Update
SOURCEandTARGET_DIRto your actual paths (e.g.,TARGET_DIR="/home/user/backups") - Save the file as
copy_test.sh - Make it executable:
chmod +x copy_test.sh - Run it:
./copy_test.sh
Key Details to Note
- The
grep -Efilter ensures we only match folders named exactlytest,test1throughtest10(avoids accidental matches liketest11ortest_backup) 2>/dev/nullsuppresses error messages if no existingtest*folders are foundcp -rpuses recursive copy (-r) and preserves file permissions, timestamps, and other attributes (-p)- The numbering loops back to
testaftertest10, exactly as you requested
内容的提问来源于stack exchange,提问作者Björn
相关产品推荐
相关产品推荐

