35

I'm running some third-party Perl script written such that it requires an output file for the output flag, -o.

Unfortunately, the script appears to require an actual file, that is, users must create an empty file filename.txt with 0 bytes and then input this empty file on the script command line

perl script1.pl -o filename.txt

Question: How would I create an empty file within a bash script? If one simply tries perl script1.pl -o filename.txt, the script gives an error that the file doesn't exist.

ilkkachu
  • 138,973

5 Answers5

45

Use touch command. touch filename.txt.

MKT
  • 5,951
15

The shortest way:

>filename
12

Use the null command (:) redirect (> filename) trick (:>), as this will truncate to zero or create the named file.

$ echo foo > filea
$ :> filea
$ wc -c filea
       0 filea
$ rm filea
$ :> filea
$ wc -c filea
       0 filea

(This will fail if the shell sets a NOCLOBBER option.)

thrig
  • 34,938
3

You could always use perl, too.

$ stat filename.txt
stat: cannot stat 'filename.txt': No such file or directory
$ perl -e 'open($fh,">","filename.txt") or die $!;close($fh)'                                         
$ stat filename.txt                                                                                   
  File: 'filename.txt'
  Size: 0           Blocks: 0          IO Block: 4096   regular empty file
Device: 801h/2049d  Inode: 280728      Links: 1
Access: (0664/-rw-rw-r--)  Uid: ( 1000/ xieerqi)   Gid: ( 1000/ xieerqi)
Access: 2017-02-08 13:51:01.479121995 -0700
Modify: 2017-02-08 13:51:01.479121995 -0700
Change: 2017-02-08 13:51:01.479121995 -0700
 Birth: -
1

dd can be used to create an empty file as follows:

dd if=/dev/null of=filename.txt count=0

One case where dd is more useful than the other approaches is creating an EFI variable (PK) through the efivars filesystem (/sys/firmware/efi/efivars).

One some platforms and Linux distributions, the file is created with the "immutible" attribute set (shows up as the "i" flag with "lasattr"). So, any subsequent operations on the file fail.

For example, touch not only creates the file, but sets the time stamp on the file. Similarly, piping to the file with > not only creates the file, but performs additional operations that fail. The dd command does not appear to fail the same way.