5 ms·
Wonder why they advise cat /dev/null > file to empty a file rather than echo > file
by obituary_latte 7y ago
Wonder why they advise cat /dev/null > file to empty a file rather than echo > file
- Dr_Emann 7y agoBecause echo-ing into a file will make a file with 1 byte in it: a single newline character.
- oreo83 7y agoecho -n >file
- chaosite 7y agoWell, `echo > file` won't empty the file, it will have a newline in it. At the very least you'll need `echo -n > file`.
- luckman212 7y agoTrick: You can use just >file
- leviathan 7y agoI've always done it as: `> file`
- naniwaduni 7y agoOr after thinking about it for a moment, true > file. Or by its shorter name, :> file.
- hultner 7y ago`printf > file`, but there's endless ways of achieving the same thing (and that's part of the beauty).
- TheSoftwareGuy 7y agoor why not `touch file`?
- finnh 7y agoThat 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.
- czr 7y agoIMO, the most natural method is simply: >file
- lasereyes136 7y agoThis 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.
- deleted 7y ago[deleted]
- harleypig 7y agoOr why they aren't recommending 'truncate -s 0 file'