18

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.

29

Use touch command. touch filename.txt.

  • 8
    echo -n >file – Hannu Feb 8 '17 at 21:48
  • 8
    take care - this will not empty your file if it already exists – johanvdw Jun 25 '18 at 11:30
6

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.)

  • 1
    If noclobber is set, use the redirection >| to clobber, so :>| filea -- documented in the manual – glenn jackman Feb 8 '17 at 20:21
  • 1
    Just > filename.txt would do, no need for the :. Or >> filename.txt if we don't want to trash it if it does happen to exist. – ilkkachu Feb 8 '17 at 21:57
  • 2
    @ilkkachu although the question does specify Bash, using : does make the script more likely to accomplish its task with other shells e.g. Zsh. – can-ned_food Feb 19 '17 at 9:22
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: -

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.