Module Script Examples
About 1763 wordsAbout 6 min
2026-01-30
This document provides common FolkPatch module script examples that you can copy or modify as needed.
Example 1: Auto Modify Hosts on Boot
Purpose: Automatically replace the system hosts file at boot to block ads or access specific websites.
Script File: service.sh
#!/system/bin/sh
# Auto modify hosts file
MODDIR=${0%/*}
LOGFILE=/data/local/tmp/hosts_changer.log
log_msg() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> $LOGFILE
}
log_msg "=== Hosts Modifier Script Started ==="
# Wait for system to fully boot
sleep 30
# Custom hosts content
CUSTOM_HOSTS="$MODDIR/hosts_custom"
# Check if custom hosts file exists
if [ -f "$CUSTOM_HOSTS" ]; then
log_msg "Custom hosts file found"
# Backup original hosts (if backup doesn't exist)
if [ ! -f /system/etc/hosts.bak ]; then
cp /system/etc/hosts /system/etc/hosts.bak
log_msg "Original hosts file backed up"
fi
# Mount custom hosts over system hosts (systemless way)
mount -o bind "$CUSTOM_HOSTS" /system/etc/hosts
if [ $? -eq 0 ]; then
log_msg "Hosts file modified successfully"
else
log_msg "ERROR: Failed to modify hosts file"
fi
else
log_msg "WARNING: Custom hosts file not found"
fi
log_msg "=== Script Execution Completed ==="Companion File: hosts_custom
Create a hosts_custom file in the same module directory:
# Custom hosts file
# Ad blocking example
127.0.0.1 ad.example.com
127.0.0.1 analytics.example.com
0.0.0.0 tracking.example.com
# Other custom entries...Installation Steps
Create a module package containing:
module.propservice.sh(script above)hosts_custom(your hosts content)
Install the module in FolkPatch Manager
Reboot the device
Example 2: Modify System Properties
Purpose: Modify Android system properties, such as displaying a custom ROM name, modifying device model, etc.
Script File: service.sh
#!/system/bin/sh
# System property modification example
MODDIR=${0%/*}
LOGFILE=/data/local/tmp/prop_modifier.log
log_msg() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> $LOGFILE
}
log_msg "=== Property Modifier Script Started ==="
# Wait for system services to start
sleep 10
# Modify ROM display name
resetprop ro.build.display.id "My Awesome ROM v2.0"
log_msg "Modified ro.build.display.id"
# Modify device model (Note: This may affect some apps)
# resetprop ro.product.model "Custom Model"
# log_msg "Modified ro.product.model"
# Modify manufacturer
# resetprop ro.product.manufacturer "Custom Brand"
# log_msg "Modified ro.product.manufacturer"
# Modify Android version display (Display only, does not change actual version)
# resetprop ro.build.version.release "14"
# log_msg "Modified ro.build.version.release"
# Modify security patch date display
# resetprop ro.build.version.security_patch "2099-12-31"
# log_msg "Modified ro.build.version.security_patch"
# Check modified properties
log_msg "Current display version: $(getprop ro.build.display.id)"
log_msg "=== Property Modification Completed ==="Installation Steps
- Create module directory:
/data/adb/modules/prop_modifier/ - Create
module.propfile - Save the script above as
service.sh - Set execution permission:
chmod +x service.sh - Reboot device
Example 3: Auto Release Memory
Purpose: Periodically clean background processes to release memory (use with caution).
Script File: service.sh
#!/system/bin/sh
# Auto memory cleaner service
MODDIR=${0%/*}
LOGFILE=/data/local/tmp/memory_cleaner.log
log_msg() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> $LOGFILE
}
log_msg "=== Memory Cleaner Service Started ==="
# Run loop in background
(
# Wait for system to fully boot
sleep 120
while true; do
# Get current memory usage
MEM_INFO=$(cat /proc/meminfo | grep MemAvailable)
MEM_AVAILABLE=$(echo $MEM_INFO | awk '{print $2}')
MEM_TOTAL=$(cat /proc/meminfo | grep MemTotal | awk '{print $2}')
# Calculate available memory percentage
MEM_PERCENT=$((MEM_AVAILABLE * 100 / MEM_TOTAL))
log_msg "Current available memory: ${MEM_PERCENT}%"
# If available memory is below 15%, perform cleanup
if [ $MEM_PERCENT -lt 15 ]; then
log_msg "Low memory, starting cleanup..."
# Drop caches
echo 3 > /proc/sys/vm/drop_caches
log_msg "System caches cleaned"
# Check memory after cleanup
MEM_INFO_AFTER=$(cat /proc/meminfo | grep MemAvailable)
MEM_AVAILABLE_AFTER=$(echo $MEM_INFO_AFTER | awk '{print $2}')
MEM_PERCENT_AFTER=$((MEM_AVAILABLE_AFTER * 100 / MEM_TOTAL))
log_msg "Available memory after cleanup: ${MEM_PERCENT_AFTER}%"
fi
# Check every 10 minutes
sleep 600
done
) &
log_msg "=== Memory Cleaner Service running in background ==="Note
- This script periodically clears system caches, which may affect app performance
- Not recommended for low-memory devices
- Adjust cleanup threshold and interval as needed
Example 4: Execute Shell Command at Boot
Purpose: Execute arbitrary commands or scripts automatically at system boot.
Script File: service.sh
#!/system/bin/sh
# Execute custom commands at boot
MODDIR=${0%/*}
LOGFILE=/data/local/tmp/startup_commands.log
log_msg() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> $LOGFILE
}
log_msg "=== Startup Commands Script Started ==="
# Wait for system to fully boot
sleep 20
# Example 1: Create a specific file flag
log_msg "Creating boot flag file"
touch /data/local/tmp/boot_completed.flag
# Example 2: Modify file permissions
log_msg "Modifying specific file permissions"
chmod 644 /data/local/tmp/some_config.txt 2>/dev/null || log_msg "File not found, skipping"
# Example 3: Delete temporary files
log_msg "Cleaning temporary files"
rm -f /data/local/tmp/old_*.tmp 2>/dev/null && log_msg "Temporary files cleaned" || log_msg "No temporary files to clean"
# Example 4: Set CPU frequency (Requires kernel support)
# log_msg "Setting CPU performance mode"
# echo performance > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null || log_msg "Unable to set CPU performance mode"
# Example 5: Start custom service
# if [ -x "$MODDIR/my_service.sh" ]; then
# log_msg "Starting custom service"
# nohup sh "$MODDIR/my_service.sh" > /dev/null 2>&1 &
# fi
# Example 6: Log boot info
log_msg "System boot completed, logging info"
echo "Boot time: $(date)" >> $LOGFILE
echo "Device: $(getprop ro.product.model)" >> $LOGFILE
echo "Android version: $(getprop ro.build.version.release)" >> $LOGFILE
log_msg "=== Startup Commands Execution Completed ==="Example 5: SELinux Policy Patch
Purpose: Add SELinux permissions for specific apps or services.
File 1: sepolicy.rule
Create sepolicy.rule file in the module root directory:
# Allow my_app to access specific service
allow my_app system_server_service service_manager find
# Allow shell to execute specific operations (Example)
# allow shell my_custom_file file { read write }
# Allow app to read logs
# allow my_app logd unix_stream_socket connecttoImportant
- Writing SELinux policies requires professional knowledge
- Incorrect rules may lead to security vulnerabilities or system instability
- Recommended to refer to default system policies for modification
File 2: service.sh (Optional, for verification)
#!/system/bin/sh
# Verify SELinux status
MODDIR=${0%/*}
LOGFILE=/data/local/tmp/selinux_check.log
echo "[$(date)] SELinux Status Check" >> $LOGFILE
echo "Current mode: $(getenforce)" >> $LOGFILE
echo "Policy version: $(cat /sys/fs/selinux/policyvers 2>/dev/null || echo 'N/A')" >> $LOGFILEExample 6: Conditional Script Execution
Purpose: Decide whether to execute based on device model, Android version, or other conditions.
Script File: service.sh
#!/system/bin/sh
# Conditional execution script
MODDIR=${0%/*}
LOGFILE=/data/local/tmp/conditional_script.log
log_msg() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> $LOGFILE
}
log_msg "=== Conditional Script Started ==="
# Get device info
DEVICE=$(getprop ro.product.device)
MODEL=$(getprop ro.product.model)
ANDROID_VERSION=$(getprop ro.build.version.release)
SDK_VERSION=$(getprop ro.build.version.sdk)
log_msg "Device Info:"
log_msg " Device: $DEVICE"
log_msg " Model: $MODEL"
log_msg " Android: $ANDROID_VERSION (API $SDK_VERSION)"
# Condition 1: Execute only on specific device
if [ "$DEVICE" = "your_device_codename" ]; then
log_msg "Target device detected, executing specific operations"
# Add specific device operations here
else
log_msg "Non-target device, skipping specific operations"
fi
# Condition 2: Execute only on Android 11 and above
if [ "$SDK_VERSION" -ge 30 ]; then
log_msg "Android 11+ detected, executing advanced features"
# Add Android 11+ operations here
else
log_msg "Lower Android version, using compatibility mode"
fi
# Condition 3: Check if specific file exists
if [ -f /system/etc/some_config.xml ]; then
log_msg "Config file found, executing related operations"
# Add related operations here
else
log_msg "Config file not found, skipping"
fi
# Condition 4: Check if specific app is installed
if pm list packages | grep -q "com.example.app"; then
log_msg "Target app detected, executing app related operations"
# Add app related operations here
else
log_msg "Target app not installed"
fi
log_msg "=== Script Execution Completed ==="Example 7: Module Uninstall Cleanup
Purpose: Execute cleanup operations when the module is uninstalled.
Script File: uninstall.sh
#!/system/bin/sh
# Cleanup on module uninstall
LOGFILE=/data/local/tmp/module_uninstall.log
echo "[$(date)] Module uninstall started" >> $LOGFILE
# Clean log files
rm -f /data/local/tmp/module_*.log
# Restore backed up files (if any)
if [ -f /system/etc/hosts.bak ]; then
echo "[$(date)] Restoring hosts backup" >> $LOGFILE
# Note: This is just an example, actual operation may require mounting system
# cp /system/etc/hosts.bak /system/etc/hosts
fi
# Delete created flag files
rm -f /data/local/tmp/boot_completed.flag
echo "[$(date)] Module uninstall completed, cleanup executed" >> $LOGFILEHint
uninstall.sh executes automatically when the module is uninstalled, no manual permission setting required.
Example 8: Action Button Script
Purpose: Provide a script that can be manually executed in the manager.
Script File: action.sh
#!/system/bin/sh
# Action Button Script - For manual trigger of specific operations
MODDIR=${0%/*}
LOGFILE=/data/local/tmp/action_script.log
echo "[$(date)] Action script execution started" >> $LOGFILE
# Show selection menu (via log output)
echo "Please select operation to execute:"
echo "1. Clean system cache"
echo "2. Restart specific service"
echo "3. Backup current config"
# Example Operation 1: Clean cache
clean_cache() {
echo "Cleaning system cache..."
echo 3 > /proc/sys/vm/drop_caches
echo "Cache cleanup completed"
echo "[$(date)] System cache cleaned" >> $LOGFILE
}
# Example Operation 2: Restart service (Example, actual service name required)
restart_service() {
echo "Restarting service..."
# am restart or other service management command
echo "Service restart completed"
echo "[$(date)] Service restarted" >> $LOGFILE
}
# Example Operation 3: Backup config
backup_config() {
BACKUP_DIR=/sdcard/ModuleBackup
mkdir -p $BACKUP_DIR
echo "Backing up config..."
cp -r /data/adb/modules/$MODID $BACKUP_DIR/
echo "Config backed up to: $BACKUP_DIR"
echo "[$(date)] Config backed up to $BACKUP_DIR" >> $LOGFILE
}
# Execute default operation (Clean cache)
clean_cache
echo "[$(date)] Action script execution completed" >> $LOGFILEUsage
- Enter module details in FolkPatch Manager
- Click "Execute Action" button
- View execution result and log
Template: General Module Framework
Here is a complete module template containing all common files:
File Structure:
my_module/
├── module.prop
├── customize.sh (Optional)
├── service.sh
├── post-fs-data.sh (Optional)
├── uninstall.sh (Optional)
├── action.sh (Optional)
├── system.prop (Optional)
├── sepolicy.rule (Optional)
└── system/ (Optional, for file mounting)module.prop:
id=my_custom_module
name=My Custom Module
version=v1.0.0
versionCode=100
author=Your Name
description=This is a custom module for demonstrating module developmentservice.sh:
#!/system/bin/sh
# General service script template
MODDIR=${0%/*}
LOGFILE=/data/local/tmp/my_module.log
# Log function
log_msg() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> $LOGFILE
}
log_msg "=== Module Service Started ==="
log_msg "Module Path: $MODDIR"
# Wait for system boot
sleep 20
# TODO: Add your script logic here
log_msg "Executing custom operations..."
# Example: Check module status
if [ -f "$MODDIR/disable" ]; then
log_msg "Module is disabled"
else
log_msg "Module running normally"
fi
log_msg "=== Module Service Completed ==="Debugging Tips
Add Detailed Logs in Script
#!/system/bin/sh
MODDIR=${0%/*}
LOGFILE=/data/local/tmp/debug_$(basename $0).log
# Clear old log
> $LOGFILE
log_msg() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$(basename $0)] $1" | tee -a $LOGFILE
}
log_msg "Script execution started"
log_msg "Current User ID: $(id)"
log_msg "Current Working Directory: $(pwd)"
log_msg "Module Directory: $MODDIR"
log_msg "Script Path: $0"
log_msg "Environment Variables:"
env >> $LOGFILE
# Your script logic
log_msg "Script execution completed, exit code: $?"Test Script Syntax
# Check script syntax errors
sh -n /path/to/your/script.sh
# If no output, syntax is correct
# If error exists, line number and error message will be displayedPrecautions
Performance Impact
- Avoid time-consuming operations in
post-fs-data.sh(Limit 10 seconds) service.shshould use background processes for long-running tasks
- Avoid time-consuming operations in
Security
- Do not hardcode sensitive info (e.g., passwords, keys)
- Cautiously modify system critical files
- Use
resetpropinstead of directly modifying/system/build.prop
Compatibility
- Commands and paths may differ across Android versions
- Use conditional checks for device compatibility
- Test on spare device first
Log Management
- Periodically clean log files to avoid using too much space
- Use append mode (
>>) instead of overwrite mode (>)
Related Documents
- Script Import Guide - Learn how to import scripts
- Script Management Guide - Learn how to manage scripts
Copyright
Copyright Ownership:FolkPatch Team
License under:Attribution 4.0 International (CC-BY-4.0)
