Skip to content

Instantly share code, notes, and snippets.

@approximatenumber
Created July 8, 2019 11:29
Show Gist options
  • Save approximatenumber/14698f0d676aada72685f6dcad10d4ec to your computer and use it in GitHub Desktop.
Save approximatenumber/14698f0d676aada72685f6dcad10d4ec to your computer and use it in GitHub Desktop.
Simple script to fill RAM for testing purposes
#!/bin/sh
# Script to fill RAM memory with writing zeroes to /dev/shm.
# Usage:
# ./fill_ram.sh <STEP> <THRESHOLD>
# <STEP>: filling step (%)
# <THRESHOLD>: used memory threshold (%)
# Example:
# ./fill_ram.sh 5 70
# Fill RAM with 5% step and stop filling on 70% memory used.
# Default memory step in percents
DEFAULT_STEP_PCT=10
# Default memory treshold in percents
DEFAULT_THRESHOLD_PCT=100
# Total memory
TOTAL_MEM=$(free --mega | grep -oP '\d+' | head -n 1)
# Memory step in percents
MEM_STEP_PCT="${1:-$DEFAULT_STEP_PCT}"
# Memory step in MB
MEM_STEP=$(expr $TOTAL_MEM \* $MEM_STEP_PCT / 100)
# Memory treshold in percents
MEM_THRESHOLD_PCT="${2:-$DEFAULT_THRESHOLD_PCT}"
# Memory treshold in MB
MEM_THRESHOLD="$(expr $TOTAL_MEM \* $MEM_THRESHOLD_PCT / 100)"
# Used memory
get_used_mem(){
shared=$(free --mega --total | grep -oP '\d+' | head -4 | tail -1)
used=$(free --mega --total | grep -oP '\d+' | tail -2 | head -1)
expr $shared + $used
}
# Keyboard interrupt handler
ctrl_c() {
rm -rf /dev/shm/fill_*
echo "Memory cleaned."
exit
}
trap ctrl_c INT
echo -n "Total memory: $TOTAL_MEM MB. "
echo -n "Used memory: $(get_used_mem) MB. "
echo -n "Memory filling step: $MEM_STEP MB ($MEM_STEP_PCT%). "
echo -n "Threshold: $MEM_THRESHOLD MB ($MEM_THRESHOLD_PCT%). "
echo -n "Hit Ctrl+C to stop.\n"
sleep 3
range=$(expr $TOTAL_MEM / $MEM_STEP)
for i in $(seq $range); do
if [ $(get_used_mem) -ge $MEM_THRESHOLD ]; then
echo "Threshold reached. Hit Ctrl+C to clean memory."
sleep infinity
fi
dd if=/dev/zero of=/dev/shm/fill_$i bs=1M count=$MEM_STEP status=none
echo "Written $MEM_STEP MB to /dev/shm/fill_$i. Used: $(get_used_mem) MB."
sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment