Sometimes I see my swap file is a bit bigger then usual. I tried
sync && echo 3 > /proc/sys/vm/drop_caches to no avail. But when I tried
swapoff -a it takes a bit longer but the swap file is smaller after. How can I clear my swap file without using
3 > drop_caches instructs the kernel to discard all the cached data (that are not needed any more).
swapoff will try to pull as much of the data, that are currently on swap, as it can back into memory. It may also trigger dropping some cached pages to make room for what is coming into memory from the swap file.
You really only seldom need to do this, the kernel does a rather good job on deciding what to do with what data (e.g. if you are working with a big file it might cache it and swap out the memory allocated to some other running process that isn't very active).
I'm not sure whether you are really using a swap file as such (i.e. a file on a regular filesystem) or just misinterpreting the output of
free, but if you do, what could actually help is a dedicated swap partition, as you won't encounter any possible filesystem overhead (but the space would be reserved for kernel to use of course).
By the way, if you use
tmpfs (usually mounted at
/dev/shm and these days often at
/run and some other places as well), any files held there will show up as "cached" in