Scripting Batch Creation
Shell Script Fundamentals for Directory Management
Basic Shell Script Structure
#!/bin/bash
## Directory creation script
mkdir -p /path/to/project/{src,test,docs}
Scripting Techniques for Batch Directory Creation
Dynamic Directory Generation
#!/bin/bash
BASE_DIR="/home/labex/projects"
PROJECTS=("web" "mobile" "desktop")
for project in "${PROJECTS[@]}"; do
mkdir -p "$BASE_DIR/$project"/{src,test,config}
done
Advanced Scripting Strategies
Conditional Directory Creation
#!/bin/bash
function create_project_structure() {
local project_name=$1
if [ ! -d "$project_name" ]; then
mkdir -p "$project_name"/{src,tests,docs}
echo "Project $project_name created successfully"
else
echo "Project $project_name already exists"
fi
}
create_project_structure "myproject"
Scripting Patterns
Pattern |
Description |
Use Case |
Static List |
Predefined directories |
Simple projects |
Dynamic Generation |
Generated directories |
Complex structures |
Conditional Creation |
Checks before creation |
Preventing duplicates |
Error Handling in Scripts
Robust Directory Creation
#!/bin/bash
function safe_mkdir() {
local dir_path=$1
if mkdir -p "$dir_path" 2>/dev/null; then
echo "Created: $dir_path"
else
echo "Failed to create: $dir_path" >&2
return 1
fi
}
safe_mkdir "/home/labex/projects/new_project"
Scripting Workflow
graph TD
A[Start Script] --> B{Check Conditions}
B --> |Valid| C[Create Directories]
B --> |Invalid| D[Exit/Error Handling]
C --> E[Verify Creation]
E --> F[Log Results]
F --> G[End Script]
Advanced Script Techniques
Parameterized Directory Creation
#!/bin/bash
PROJECT_BASE="/home/labex/workspace"
DEPTH=${1:-3} ## Default depth of 3 if not specified
generate_nested_dirs() {
local base_path=$1
local current_depth=$2
if [ $current_depth -le 0 ]; then
return
fi
mkdir -p "$base_path/level_$current_depth"
generate_nested_dirs "$base_path/level_$current_depth" $((current_depth - 1))
}
generate_nested_dirs "$PROJECT_BASE/dynamic_project" "$DEPTH"
Best Practices with LabEx
- Use functions for reusability
- Implement error checking
- Log directory creation processes
- Use parameterization for flexibility
By mastering scripting batch creation techniques, you'll efficiently manage complex directory structures in your Linux environment with LabEx.