tags:

views:

60

answers:

5

I want to empty 3 files or generate them if they do not exist. Is the following command correct?

> myone.txt > mytwo.txt > mythree.txt

or is there any better way?

+1  A: 

No, not from the shell. Reading the generated system calls for this, it's also pretty efficient for a shell builtin:

matt@stanley:~$ strace bash -c '> a > b > c'
...
open("a", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 3
fcntl64(1, F_GETFD)                     = 0
fcntl64(1, F_DUPFD, 10)                 = 10
fcntl64(1, F_GETFD)                     = 0
fcntl64(10, F_SETFD, FD_CLOEXEC)        = 0
dup2(3, 1)                              = 1
close(3)                                = 0
open("b", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 3
fcntl64(1, F_GETFD)                     = 0
fcntl64(1, F_DUPFD, 10)                 = 11
fcntl64(1, F_GETFD)                     = 0
fcntl64(11, F_SETFD, FD_CLOEXEC)        = 0
dup2(3, 1)                              = 1
close(3)                                = 0
open("c", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 3
fcntl64(1, F_GETFD)                     = 0
fcntl64(1, F_DUPFD, 10)                 = 12
fcntl64(1, F_GETFD)                     = 0
fcntl64(12, F_SETFD, FD_CLOEXEC)        = 0
dup2(3, 1)                              = 1
close(3)
Matt Joiner
+1  A: 

I usually use touch to create empty files. It is usually cast as a utility to update timestamps, but also will create the named file if it does not exist.

Alex JL
Will it empty the file contents if the file already exist?
shantanuo
no. it will not
ghostdog74
Hmm, good point. I just caught the 'generate' part of the question...
Alex JL
+3  A: 

you can use touch to create empty files if there haven't existed. Otherwise, what you are doing is all right

>file1 >file2 
ghostdog74
+1  A: 

Alternative to touch is using dd which can be used to truncate existing files,

dd if=/dev/null of=moo count=0
Steve-o
+1  A: 

One thing that you can't do with > is something like >file{0..9} or >file{foo,bar,baz}. However, if your system has truncate you can do this:

truncate --size 0 file{0..9}
truncate --size 0 file{foo,bar,baz}

By using different arguments with --size you can shrink or extend a file, but it doesn't empty it first unless you use 0 for the size (in the first of two passes, for example). Extended files are padded with nulls.

Dennis Williamson