BASH脚本while循环中写入文件realpath至RESULTS.txt为空的解决方法
You’re spot-on about the core issue—using > instead of >> is why your RESULTS.txt ends up empty (or only holds the last file’s path if the loop completes). Here’s a breakdown of what’s happening and how to fix it:
Why > Breaks Things
The > redirection operator wipes the target file clean every time you use it. So in each loop iteration, you’re replacing the entire contents of RESULTS.txt with just the current file’s realpath. If the loop exits early or there’s an issue with the final file, you might end up with an empty file entirely.
The Simple Fix: Use >> to Append
Replace this line:
realpath "$filename" > RESULTS.txt
With:
realpath "$filename" >> RESULTS.txt
The >> operator adds new content to the end of the file instead of overwriting it. This way, every processed file’s realpath gets added as a new line in RESULTS.txt.
Optional: Start with a Clean Slate
To ensure RESULTS.txt is empty before your script runs (in case old content exists from a previous execution), add this line right before your while loop:
> RESULTS.txt # Truncate the file to empty before starting
Corrected Code Snippet
Here’s how the fixed section of your script will look:
> RESULTS.txt # Optional: Clear existing content first while read -r filename do filecount=$((filecount+1)) tput rc # 返回光标至之前保存的终端行(tput sc) # 输出文件名(输出第一行);若比上一个文件名短则需清除行剩余内容 filename="${filename%$'\r'}" printf "file: ${filename}${erase}\n" realpath "$filename" >> RESULTS.txt # Fixed: Append instead of overwrite # 在首次及每经过${modcount}次循环时输出状态条(输出第二行); if [ ${filecount} -eq 1 ] then printf "[${barhash}${barspace}]\n" elif [[ $((filecount % ${modcount} )) -eq 0 ]] then # 每处理第${modcount}个文件时... barspace=${barspace:1:100000} # 移除barspace中的一个空格 barhash="${barhash}#" # 向barhash添加一个'#' printf "[${barhash}${barspace}]\n" # 输出新状态条 fi done < <(find "$dir_choice" -type f | sort -V )
This should resolve the issue and populate RESULTS.txt with all the realpaths of the files your loop processes.
内容的提问来源于stack exchange,提问作者dex

