#!/bin/zsh tempFile=`mktemp test.XXXXXX` exec 3>${tempFile} echo "This is the first line" >&3 echo "This is the second line" >&3 echo "This is the last line" >&3 exec 3>&- cat ${tempFile} rm -f ${tempFile} 2> /dev/null
return
1 2 3 4
❯ ./file.sh This is the first line This is the second line This is the last line
注意mktemp 命令创建临时文件的时候
mktemp命令要求模板中包含至少 6 个X
创建临时目录
1 2 3 4 5 6 7 8 9
#!/bin/zsh tempFile=mktemp -d dir.XXXXXX cd ${tempFile}|exit 1 tempFile1=mktemp temp.XXXXXX tempFile2=mktemp temp2.XXXXXX exec 7> ${tempFile1} exec 8> ${tempFile2} echo "This is a test line of data for $tempFile1" >&7 echo "This is a test line of data for $tempFile2" >&8
# 打开文件描述符并向临时文件写入数据 exec 7> "${tempFile1}" exec 8> "${tempFile2}" echo "This is a test line of data for $tempFile1" >&7 echo "This is a test line of data for $tempFile2" >&8
# 关闭文件描述符 exec 7>&- exec 8>&-
# 显示临时文件内容 echo "Contents of $tempFile1:" cat "${tempFile1}"
echo "Contents of $tempFile2:" cat "${tempFile2}"
# 删除临时文件 rm -f "${tempFile1}" "${tempFile2}"
# 删除临时目录 rmdir "${tempFile}" || echo "Failed to remove directory ${tempFile}: It may not be empty."