如何根据用户选择在批量创建的文件夹中生成编号序列文件?
Fixing Your Script to Generate Numbered Files in Each Folder
Let's get your script working exactly how you want it—creating a set number of folders, each filled with sequentially numbered files. Here's what was missing in your original code, plus the corrected version:
Issues in the Original Script
- The
DIRYvariable wasn't defined or initialized (we need to know where to create these folders!) - The second
forloop had incorrect syntax, and it wasn't nested inside the folder-creation loop (so it wasn't targeting each new folder) - No handling for cases where the target directory might not exist
Corrected Script
# Ask user for target directory (where folders will be created) read -p "Enter the target directory path: " DIRY # Ensure the target directory exists (create it if not) mkdir -p "$DIRY" # Get number of folders and files per folder from user read -p "Enter the number of folders to create: " FOLDER_X read -p "Enter the number of files to create per folder: " FILE_Y # Loop to create each folder, then add numbered files inside for (( x = 1; x <= FOLDER_X; x++ )); do # Define the full path for the current folder FOLDER_PATH="$DIRY/$x" mkdir -p "$FOLDER_PATH" # Loop to create numbered files in this folder for (( i = 1; i <= FILE_Y; i++ )); do # Create file with sequential number, write content to it echo "hello" > "$FOLDER_PATH/$i.txt" done done
Key Improvements Explained
- Target Directory Handling: We first ask for the directory where folders should live, and use
mkdir -pto make sure it exists (no errors if it's already there) - Nested Loops: The file-creation loop is now inside the folder-creation loop, so each folder gets its own set of files
- Sequential Numbering: The inner loop runs from 1 to
FILE_Y, creating files named1.txt,2.txt, etc., directly in the corresponding folder - Quoted Paths: All paths are wrapped in quotes (
"$FOLDER_PATH") to handle spaces or special characters in directory names
Just run this script, input your desired values, and it'll generate exactly the structure you need!
内容的提问来源于stack exchange,提问作者Modo
相关产品推荐
相关产品推荐

