How to generate a memory shortage using bash script
bash, esxi, shell
Solution
From an earlier answer of mine: https://unix.stackexchange.com/a/254976/30731
If you have basic GNU tools (`head` and `tail`) or BusyBox on Linux, you can do this to fill a certain amount of free memory:
</dev/zero head -c BYTES | tail
# Protip: use $((1024**3*7)) to calculate 7GiB easily
</dev/zero head -c $((1024**3*7)) | tail
This works because tail needs to keep the current line in memory, in case it turns out to be the last line. The line, read from `/dev/zero` which outputs only null bytes and no newlines, will be infinitely long, but is limited by `head` to `BYTES` bytes, thus `tail` will use only that much memory. For a more precise amount, you will need to check how much RAM `head` and `tail` itself use on your system and subtract that.
To just quickly run out of RAM completely, you can remove the limiting `head` part:
tail /dev/zero
If you want to also add a duration, this can be done quite easily in `bash` (will not work in `sh`):
cat <( </dev/zero head -c BYTES) <(sleep SECONDS) | tail
The `<(command)` thing seems to be little known but is often extremely useful, more info on it here: http://tldp.org/LDP/abs/html/process-sub.html
Then for the use of `cat`: `cat` will wait for inputs to complete until exiting, and by keeping one of the pipes open, it will keep `tail` alive.
If you have `pv` and want to slowly increase RAM use:
</dev/zero head -c BYTES | pv -L BYTES_PER_SEC | tail
For example:
</dev/zero head -c $((1024**3)) | pv -L $((1024**2)) | tail
Will use up to a gigabyte at a rate of a megabyte per second. As an added bonus, `pv` will show you the current rate of use and the total use so far. Of course this can also be done with previous variants:
</dev/zero head -c BYTES | pv | tail
Just inserting the `| pv |` part will show you the current status (throughput and total by default).
Credits to falstaff for contributing a variant that is even simpler and more broadly compatible (like with BusyBox).
Problem
I need to write a bash script that would consume a maximum of RAM of my ESXi and potentially generate a memory shortage. I already checked here and try to run the given script several times so that I can consume more thant 500Mb of RAM. However I get a "sh: out of memory" error (of course) and I'd like to know if there is any possibility to configuration the amount of memory allocated to my shell ? - Note1 : Another requirement is that I cannot enter a VM a run a greedy task. - Note2 : I tried to script the creation of greedy new VMs with huge RAM however I cannot get to ESXi state where there is a shortage of memory. - Note3 : I cannot use a C compiler and I only have very limited python library. Thank you in advance for your help :)