我正在尝试找到正确的解决方案来删除我用来使用 bash 获取 sqlplus 的 SELECT 查询结果的临时文件。由于我无法按照格式创建所需的输出文件,因此我首先将结果存储在文件中,然后对其进行处理并将其附加到目标文件中。我应该如何命名临时文件才能删除当前 bash 进程的确切文件?我什至通过附加进程 ID 名称来命名临时文件,但进程太多,可以同时创建相同的进程 ID 文件。
SQL_FILE=/sql/transaction.sql
#Create tep
Pid=$$
TEMP_FILE=${TEMP_FILE_PATH}/output_$Pid.txt
$ORACLE_HOME/bin/sqlplus ${ORA_USER}/${ORA_PASS}@${SQL_PLUS_IP}:${SQL_PLUS_PORT}/${ORA_SID} @${SQL_FILE} ${TEMP_FILE}
#After Processing
rm -f ${TEMP_FILE}
exit 0
output_$Pid.txt 临时文件用于假脱机 sql 查询的输出。
最佳答案
继续评论,除了创建临时文件并设置陷阱
以在终止、中断或退出时删除临时文件之外,您还应该验证整个过程中的每个步骤。您应该验证 mktemp
是否提供了零退出代码。您应该验证临时文件确实已创建。然后您就可以放心地使用临时文件,不会发生任何中间错误。
一个简短的例子是:
#!/bin/bash
tmpfile=$(mktemp) ## create temporary file
[ "$?" -eq 0 ] || { ## validate zero exit code from mktemp
printf "error: mktemp had non-zero exit code.\n" >&2
exit 1
}
[ -f "$tmpfile" ] || { ## validate temp file actually created
printf "error: tempfile does not exist.\n" >&2
exit 1
}
## set trap to remove temp file on termination, interrupt or exit
trap 'rm -f "$tmpfile"' SIGTERM SIGINT EXIT
## Your Script Content Goes Here, below simply exercises the temp file as an example
## fill temp file with heredoc to test
cat > "$tmpfile" << eof
The temporary file was successfully create at: '$tmpfile'.
The temporary file will be removed by a trap function when this
script is terminated or interrupted, or when this script exits
normally.
eof
cat "$tmpfile" ## output temp file to terminal
有几种方法可以解决这个问题。这只是一种简单、非退出的方式,将各个部分组合在一起并进行验证,以确保一切按照您的预期发生。
关于bash - 创建用于 bash 输出处理的临时文本文件并在进程结束后删除该文件的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66059142/