如何避免重复echo/printf语句,实现条件输出至文件并消除重复代码?
Hey there! Let's tackle your two questions together—both are about cutting down on repetitive code, which is always a smart move to keep scripts clean and maintainable.
通用思路:避免重复编写echo/printf的核心方法
Here are three solid approaches to avoid duplicating output statements while handling conditional file writes:
- 暂存输出内容到变量:先把要输出的文本存入变量,再分别处理屏幕输出和条件性文件写入。这是最直观的方法,适合单次场景。
- 封装逻辑到函数:把输出+条件写入的逻辑做成一个可复用的函数,在需要的地方调用即可。完美适合多处需要相同逻辑的脚本。
- 利用管道+条件
tee:通过管道将输出内容导向tee(条件满足时同时写文件和屏幕)或cat(仅输出到屏幕),这样输出语句只需写一次。
针对你的代码的具体优化
Let's apply these to your existing code. First, here's your original snippet (formatted for clarity):
if (( qs <= 99999 )); then printf "${sp[x]} bonus is = £0 for ${qs[i]} QuarterlySales\n" if [ "$save" = "y" ]; then printf "${sp[x]} bonus is = £0 for ${qs[i]} QuarterlySales\n" >> records.txt fi fi
优化方案1:使用变量暂存内容
if (( qs <= 99999 )); then # 把要输出的内容存到变量里 output_text="${sp[x]} bonus is = £0 for ${qs[i]} QuarterlySales" # 输出到屏幕 printf "%s\n" "$output_text" # 条件满足时写入文件 if [ "$save" = "y" ]; then printf "%s\n" "$output_text" >> records.txt fi fi
This way, you only define the output string once, and reuse it for both screen and file output.
优化方案2:封装成可复用函数
If you find yourself needing this logic multiple times in your script, a function will save you even more hassle:
# 先定义函数,处理输出和条件写入 print_and_save() { local content="$1" # 先输出到屏幕 printf "%s\n" "$content" # 如果save为y,追加到文件 if [ "$save" = "y" ]; then printf "%s\n" "$content" >> records.txt fi } # 然后在你的逻辑里调用函数 if (( qs <= 99999 )); then print_and_save "${sp[x]} bonus is = £0 for ${qs[i]} QuarterlySales" fi
Now you can call print_and_save anywhere in your script with different content, no more duplicating printf lines!
优化方案3:管道+条件tee(最简洁的单次写法)
This approach lets you write the printf statement only once, using a conditional pipe to handle the file write:
if (( qs <= 99999 )); then printf "%s\n" "${sp[x]} bonus is = £0 for ${qs[i]} QuarterlySales" | if [ "$save" = "y" ]; then # tee -a 同时输出到屏幕和追加到文件 tee -a records.txt else # cat 只输出到屏幕(相当于直接传递内容) cat fi fi
Here, the printf runs once, and the pipe decides whether to duplicate the output to the file or just send it to your terminal.
内容的提问来源于stack exchange,提问作者MONKAX

