How do I create small files in Bash?
cat with a heredoc
The heredoc allows you to type the contents of a file you are creating on the command line or even create a file with a bash script. The heredoc, created by <<
, is piped into cat
, which then redirects into the file, demofoo
:
$ cat > demofoo <<- "EOF"
> Something
> Something else
> EOF
The -
after <<
and the "
on EOF
are optional. The -
allows for tabs to indent and set the text off the 0 column, making it easier to visually parse. The "
prevents parameter expansion, command substitution, and arithmetic expansion, and essentially ensures literal interpretation of the text.
And now:
$ cat demofoo
Something
Something else
I find this useful when I want to demonstrate creating a file with static text - and thus I find this superior to writing:
in demofoo:
Something
Something else
Not only is the heredoc unambiguous, it's executable code - and it
redirect from cat input to a file
You can avoid the EOF
-type characters in an interactive bash session, but this is not conducive to scripts, since you need Ctrl-d.
for example:
~$ cat > foo.py
and hit enter. This command tells cat to redirect the output to the file foo.py, which if it already exists, would overwrite it. If I wanted to append my lines, I could use >>
instead.
I then type (with enter at the end of every line) for example:
Something
Something else
or just paste in from the example code, and when I'm done entering my lines into the file, I hit Ctrl-d
.
So that's how I quickly create new files on the bash command line.