Automatically Put Files Into a YYYY/MM Directory Structure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#!/usr/bin/env bash ## This script will find .sql and .gz files in the current ## directory and move them into YYYY/MM directories (created ## automatically). BASE_DIR=$(pwd) ## Find all .sql and .gz files in the current directory find "$BASE_DIR" -maxdepth 1 -type f -name "*.sql" -o -name "*.gz" | while IFS= read -r file; do ## Get the file's modification year year=$(date -d "$(stat -c %y $file)" +%Y) ## Get the file's modification month month=$(date -d "$(stat -c %y $file)" +%m) ## Create the YYYY/MM directories if they don't exist. The -p flag ## makes 'mkdir' create the parent directories as needed so ## you don't need to create $year explicitly. [[ ! -d "$BASE_DIR/$year/$month" ]] && mkdir -p "$BASE_DIR/$year/$month"; ## Move the file mv "$file" "$BASE_DIR/$year/$month" echo "$file" "$BASE_DIR/$year/$month" done |