用Bash多次写入文件 [英] Writing to a file multiple times with Bash
问题描述
我正在创建一个bash脚本来自动化一些命令,并且在将错误检查写入同一文件时遇到了一些麻烦。
I am creating a bash script to automate some commands and I am having some trouble writing my error checking to the same file.
#!/bin/bash
touch ErrorLog.txt
bro-cut service < conn.log | sort | uniq -c > ProtocolHierarchy.txt
if [ $? -eq 0 ]; then
echo -e "OK Protocol Hierarchy Created\n" > ErrorLog.txt
else
echo -e "FAILED Creating Protocol Hierarchy\n" > ErrorLog.txt
fi
bro-cut id.orig_h < dns.log | sort | uniq -c > AllIPAddresses.txt
if [ $? -eq 0 ]; then
echo -e "OK Created all IP Addresses\n" > ErrorLog.txt
else
echo -e "FAILED Creating all IP Addresses\n" > ErrorLog.txt
fi
目标是拥有一个我可以打开的文件,并看到所有命令均有效或失败,当前文件如下所示:
The goal being to have a file I can open and see that all the commands worked or failed, currently the file looks like this
-e OK Created all IP Addresses
当我希望它看起来像这样
When I would like it to look like this
OK Protocol Hierarchy Created
OK Created all IP Addresses
我是bash脚本真的很新,因此任何提示将不胜感激!
I am really new to bash scripting so any tips would be greatly appreciated!
推荐答案
打开一次,然后多次写入该文件描述符。
Open it once, and write to that file descriptor multiple times.
# Open (creating or truncating) the output file (only once!)
exec 3>ErrorLog.txt
# Write a line to that already-open file
echo "something" >&3
# Write a second line to that already-open file
echo "something else" >&3
# Optional: close the output file (can also be implicit when the script exits)
exec 3>&-
另一个常见的习惯用法是使用>>
以附加模式打开,但是每行执行一次
The other common idiom is to open in append mode using >>
, but doing that once per line is considerably less efficient.
# Open ErrorLog.txt, truncating if it exist, write one line, and close it
echo "something" >ErrorLog.txt
# Reopen ErrorLog.txt, write an additional line to the end, and close it again
echo "something else" >>ErrorLog.txt
将这种做法放入脚本中(并进行其他一些最佳实践的改进)如下所示:
Putting this practice to work in your script (and making some other best-practice improvements) looks like the following:
#!/bin/bash
# not related to file output, but to making sure we detect errors
# only works correctly if run with bash, not sh!
set -o pipefail ## set exit status based on whole pipeline, not just last command
# picking 3, since FD numbers 0-2 are reserved for stdin/stdout/stderr
exec 3>ErrorLog.txt
if bro-cut service <conn.log | sort | uniq -c >ProtocolHierarchy.txt; then
echo "OK Protocol Hierarchy Created" >&3
else
echo "FAILED Creating Protocol Hierarchy" >&3
fi
if bro-cut id.orig_h <dns.log | sort | uniq -c >AllIPAddresses.txt; then
echo "OK Created all IP Addresses" >&3
else
echo "FAILED Creating all IP Addresses" >&3
fi
这篇关于用Bash多次写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!