This is a bad idea. If this were useful, the Linux kernel would implement it this way. I do not believe there is a reason to change more than a few tuning parameters, as such a simple shell script most likely is not more clever than the algorithms of the kernel developers.
You basically have two cases:
- The processes in swap space are not used anyway. Why do you want to pull them back into RAM?
- There is little RAM, so they get swapped out and you pull them back into RAM. Then your system will put them into swap again as soon as possible.
So there are two main points:
- First, your system will be slow when there is too little RAM to run all your programs at once. Swap will help you to run more programs, but not to switch quickly to a rarely used one, which may be swapped out. No swap may get the rarely used one killed or send the currently used one an out-of-memory exception.
- Second, swap is a good thing and so is having stuff in swap, as you have free RAM at cost of programs you're currently not using anyway.
Despite not getting out-of-memory problems with too many programs, some programs may allocate memory based on the currently free RAM (maybe your browser will use more memcache and you can browse faster) and the kernel can use free RAM for disk caching and similiar optimizations. When you force your swap to be empty, the kernel will drop its read cache and e.g. starting a new Firefox instance will take longer than when Firefox is still in the disk cache.
If you want to tune the behaviour of the kernel, see the swappiness parameter.
Two additional ressources contributes by @peter-cordes:
If you really want to have empty swap, you can turn off swap permanently. I do not see why having it on for an hour and then emptying it has advantages over not having swap.