条件重定向附加/覆盖 [英] Conditional redirection appending / overwriting

查看:108
本文介绍了条件重定向附加/覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个条件,具体取决于我要追加还是覆盖某些文件,如下所示:

I have a condition, depending on which I want to either append or overwrite some file like this:

if [ "${CONDITION}" -eq 1 ]; then
   echo "writing some info"
   echo "${INFO1}" > "${FILE1}"
   echo "${INFO2}" > "{$FILE2}"
   ...
else
   echo "Appending some info"
   echo "${INFO1}" >> "${FILE1}"
   echo "${INFO2}" >> "{$FILE2}"
   ...
fi

问题是 if else 块相对较大(每个20行),除了重定向差异之外,它们基本上是相同的.这确实让我感到非常难过.

The thing is that if and else blocks are relatively big (20 lines each) and are essentially identical except the redirection difference. This makes me feel really bad indeed.

如何避免这种不良风格?IE.我只需要一个这样的块,并以其他方式定义添加/覆盖操作.

How can I avoid this bad style? I.e. I need to have only one block like this and define the append/overwrite action in some other way.

推荐答案

使用条件以写模式打开文件(以创建/截断文件),然后无条件附加到文件中.

Use the condition to open the files in write mode (to create/truncate them), then unconditionally append to them.

if [ "${CONDITION}" -eq 1 ]; then
    : > "${FILE1}"
    : > "${FILE2}"
    echo "writing some info"
else
    echo "appending some info"
fi

# Will create files where necessary
echo "${INFO1}" >> "${FILE1}"
echo "${INFO2}" >> "{$FILE2}"
...

这篇关于条件重定向附加/覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆