问题
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
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.
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.
回答1:
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}"
...
回答2:
Why not just have the if statement delete the log files? Then you've just one set of echoes. Or if the permissions on the logfiles are very particular you could truncate them without losing the permissions by copying /dev/null to them. Then the echos are a single set, outside the if statement. I doubt you need the echo about appending or writing?
回答3:
You can factor out the redirection part by using a subshell like:
if [ "${CONDITION}" -eq 1 ]; then
echo "writing some info"
(echo "${INFO1}"
echo "${INFO2}") > "{$FILE2}"
# ...
else
echo "Appending some info"
(echo "${INFO1}"
echo "${INFO2}") >> "{$FILE2}"
# ...
fi
and then you might refactor the code in the subshells (between the parens)
function do_echos {
echo "${INFO1}"
echo "${INFO2}"
# ...
}
if [ "${CONDITION}" -eq 1 ]; then
echo "writing some info"
(do_echos) > "{$FILE2}"
else
echo "Appending some info"
(do_echos) >> "{$FILE2}"
fi
Everything is only written in one place now and you should be able to scale it from there.
original answer
If all of the lines are identical except for the redirection line then please pull all of the lines outside of the conditional. Avoiding duplication of code is a very good idea because you can introduce bugs by changing one copy of the line and failing to realize you also need to change it somewhere else.
来源:https://stackoverflow.com/questions/32141281/conditional-redirection-appending-overwriting