1832978 Members
3121 Online
110048 Solutions
New Discussion

command difference

 
kholikt
Super Advisor

command difference

Hi,

Just wondering what is the different to reset a file to zero with the following commands.

1. cat /dev/null > file
2. > file
3. touch file

All of the above seems to achieve the same purpose however for some log it is recommended to use > file instead of cat/dev/null what is the reason for this?
abc
7 REPLIES 7
John Palmer
Honored Contributor

Re: command difference

> file causes the shell to truncate file

The cat /dev/null does precisely nothing and so can be omittred.

touch file doesn't truncate the file or change the file contents at all. It just (by default) changes the time it was last modified. However it will create an empty file if it didn't already exist.

Regards,
John
Joseph C. Denman
Honored Contributor

Re: command difference

The above answer is correct. When I want to set a file to zero. I copy /dev/null to the file.

cp /dev/null file1
If I had only read the instructions first??
James A. Donovan
Honored Contributor

Re: command difference

errr..if 'cat /dev/null' isn't supposed to work, then why does it work on mine?

# echo "Testing">test
# ll test
-rw-r--r-- 1 root sys 8 Mar 20 06:57 test
# cat /dev/null >test
# ll test
-rw-r--r-- 1 root sys 0 Mar 20 06:57 test
Remember, wherever you go, there you are...
Tracey
Trusted Contributor

Re: command difference

To truncate/archive a file I use:

mv file file.old
touch file
John Palmer
Honored Contributor

Re: command difference

Jim,

It isn't the 'cat /dev/null' that truncates the file. It's the '> file' which is actioned by the shell that does the truncating before the cat process is forked.

Regards,
John

Patrick Wallek
Honored Contributor

Re: command difference

The '> file' portion of the command line is basic output redirection. If you recall the > tells the shell to always create a new file before writing any output to it.

If you did something like 'cat /dev/null >> file' then you wouldn't see any change in the file because >> says to append. So John is correct when he says the /dev/null doesn't do anything. If you want, just think of it as a place holder in the command so that you always use the command syntax you are used to (ie. 'cat filename > another_file') which is probably what most of us are used to.
James A. Donovan
Honored Contributor

Re: command difference

John, Patrick,

thanks for clearing that up for me, i never really gave much thought to it before...to think, i've been typing all those extra characters for years now...my poor carpal-tunneled hands. :-)

Remember, wherever you go, there you are...