简介清理临时文件

你可以使用 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.