簡介清理臨時檔案

你可以使用 trap 命令捕獲訊號; 這是用 C 和大多數其他程式語言捕獲訊號的 signal()sigaction() 呼叫的 shell。

trap 最常見的用途之一是在預期和意外退出時清理臨時檔案。

不幸的是沒有足夠的 shell 指令碼這樣做:-(

#!/bin/sh

# Make a cleanup function
cleanup() {
  rm --force -- "${tmp}"
}

# Trap the special "EXIT" group, which is always run when the shell exits.
trap cleanup EXIT

# Create a temporary file
tmp="$(mktemp -p /tmp tmpfileXXXXXXX)"

echo "Hello, world!" >> "${tmp}"

# No rm -f "$tmp" needed. The advantage of using EXIT is that it still works
# even if there was an error or if you used exit.