>>>>> paul <pa...@donotuse.me.invalid> writes:
>>>>> On Mon, 7 Nov 2016 02:52:11 -0800 (PST),
wke...@gmail.com wrote:
[...]
>> Then after running this script/command, then running cat myFile.txt
>> will show nothing, and ls -al myFile.txt will show size of 0.
>> I of course know about the possibility of "rm myFile.txt; touch
>> myFile.txt", but is there a way to do it in a single command ?
> One way is
> > myFile.txt
Or, as already suggested, ">|" can be used in place of ">" so
that the command does not fail when "set -o noclobber"
("set -C") is in effect.
But please note that there's a semantic difference between
"rm && touch" and ">". Namely, "rm && touch" /replaces/ the
file with a /new/, empty one. Should the file happen to have
other names ("hardlinks"), they will still refer to the original
data; also, the original data will still be accessible by the
processes, if any, having the file open.
On the contrary, ">" (">|") replaces the file contents in place.
Any and all processes accessing that file will find it empty.
Generally, unless the intent is to, for some reason, instantly
remove the data stored in a file, it makes sense to replace one
instead. A better way to do so is to create a temporary file
and use "mv" to replace the original /atomically/; say:
## Usage: replace_with_empty FILENAME
replace_with_empty () {
## NB: mktemp(1) is non-POSIX.
rwe_f_=$(mktemp -- "$1".XXXXXXXX) \
&& mv -f -- "$rwe_f_" "$1"
}
Although that's not without a flaw, as the new file created will
be accessible only by the user. With GNU Coreutils, it's
possible to copy the access mode by adding chmod(1), and perhaps
chown(1), calls to the code above; like:
&& (chmod --reference="$1" -- "$rwe_f_" ;
chown --reference="$1" -- "$rwe_f_" ; :) \
> (exactly as written) or
> truncate -s 0 myFile.txt
Note, however, that like mktemp(1), truncate(1) is non-POSIX.
But with the GNU Coreutils version, it's possible to also use
"-c" (--no-create), so to do nothing if the file does not exist.
--
FSF associate member #7257 np. Memories and Stories -- Night Breeze