Occasionally it happens that I want to redirect output to a file, but
create that file or overwrite an existing file only if there's actually
new data available. (So I don't want to and cannot use '>' or '>>'.)
Since I haven't seen that feature in shell I usually use awk to achieve
that function by something like
... | awk -v fn="some-file" '{ print > fn }'
I used that pattern already a couple of times so that I now have it in a
local bin-directory as executable file 'cf'
# cf - conditionally create file
awk -v fn="${1:?}" '{ print > fn }'
using it in contexts like
news-process | cf latest-news
where the latest-news file gets not overwritten if there's no newer news.
Redirecting with '>' to a file in shell will always overwrite the file,
unless 'noclobber' shell option is set; in that case you need '>|' to
overwrite an existing file.
In ksh there's also the '>;' redirection available. It writes output to
a temporary file and creates/overwrites the file only if no error occurs.
The tee(1) command has also no option to create or overwrite files only conditionally if data is present, as far as I can see.
Is there some tool or shell function that I missed that does conditional overwrites as described?
To reproduce standard input to standard output as well I added option -t
so that I can see what's getting written to that file (or to process any
output further in a pipeline).
#!/bin/ksh
#
# cf - conditionally create file if data is present
t=0
while getopts ":t" opt
do
case ${opt} in
(t) t=1 ;;
(\?) printf "Usage: cf [-t] filename\n" ; exit 1 ;;
esac
done
shift OPTIND-1
fn=${1:?}
awk -v fn="${fn}" -v t="${t}" '{ print > fn } t'
I can use that function in my environment but I think it would better
fit in shell, maybe as a new shell redirection ('>@', like ksh's '>;'),
or have it as feature of existing standard tools, maybe in tee(1) with
a new option supporting this semantics, like the -a is used to support
'.
Janis
--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)