用記憶體作為暫時檔案系統是個好主意,除了速度快,也可以減少寫入 SSD 次數。但使用有點麻煩,又一直懶得動手寫 script 就拖著了 (Story of my life)。前陣子看了這篇SSD Optimization 裡面介紹的幾個工具都覺得不合用,終於決定寫一個,其實也才幾行…
適用場景:打算開始在某目錄下寫程式、頻繁編譯,或類似情況。
使用方式: tmpoverlay.sh <your project dir>
特點:
- 採用 overlay filesystem, copy-on-write, 只有改了才會紀錄,不用「整個 copy 出來用完再蓋回去」,快、也避免 buffer / tmpfs 的重複。
- trap EXIT, 理論上 Ctrl-C 結束或收到 SIGTERM 都會複製回去,不會掉資料。所以就算忘記了直接登出關機應該也 OK. (沒測過)
缺點:需要 sudo NOPASSWD
Code 如下:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
# Assuming tmpfs on $TMPDIR / /tmp | |
function cleanup { | |
echo | |
if findmnt -t overlay "$D" &>/dev/null; then | |
sudo umount -l "$D" | |
if [ -d "$UPPER" ]; then | |
if [ x"$(ls -1A ${UPPER})" != x ]; then | |
echo "Copying from upper dir to lower dir" | |
cp -av "$UPPER"/. "$D" | |
fi | |
rm -rv "$UPPER" | |
fi | |
test -d "$WORK" && sudo rm -rv "$WORK" | |
fi | |
} | |
if [ x"$1" == x ]; then | |
echo "${0} <directory>" | |
exit | |
fi | |
D=$(realpath -e "$1") | |
if [ ! -d "$D" ]; then | |
echo "${D} not a directory." | |
exit 1 | |
fi | |
UPPER=$(mktemp -d --tmpdir "$(id -u).upper.XXX") | |
WORK=$(mktemp -d --tmpdir "$(id -u).work.XXX") | |
echo "UPPER DIR: $UPPER" | |
echo "WORK DIR: $WORK" | |
trap cleanup EXIT | |
sudo mount -t overlay overlay \ | |
-olowerdir="$D",upperdir="$UPPER",workdir="$WORK" \ | |
"$D" | |
echo "Ctrl-C when you're done" | |
while true; do | |
sleep 3600 | |
done |