This will empty a file without closing or invalidating any open file handlers so you can empty things like log files without restarting the services that are populating those files.
Well, `echo > file` won't empty the file, it will have a newline in it. At the very least you'll need `echo -n > file`.
I've always done it as: `> file`
That's actually very nice, I never thought about that one.
Unfortunately, this doesn't work in fish:
> fish: Expected a command, but instead found a redirection
Right but I don't think anyone is really concerned if it runs in fish. Fish is non standard and doesn't try to adhere to bash. If we want to write fish shell scripts we can do that elsewhere
Funny how the same sentence applies to bash wrt POSIX shell in other contexts
Or after thinking about it for a moment, true > file. Or by its shorter name, :> file.
`printf > file`, but there's endless ways of achieving the same thing (and that's part of the beauty).
Trick: You can use just
>file
Because echo-ing into a file will make a file with 1 byte in it: a single newline character.
echo -n >file
Or why they aren't recommending 'truncate -s 0 file'
IMO, the most natural method is simply:
>file
or why not `touch file`?
That works to create an empty file if none exists, but if the file already exists then 'touch' simply updates its atime/mtime and doesn't alter the contents. This latter effect is actually the purpose of touch; the file creation part is just a side effect.