سؤال

Say I have a Bash script, and I want to create a file with it.

For another use-case - say I just need a file with some contents created quickly, and I don't want to leave the command line. Maybe it's just a few lines, or maybe I'm pasting in some sample code for a demonstration.

My question is:

How do you create a new file with contents on the command line in Bash?

هل كانت مفيدة؟

المحلول

It's similar to your 'cat' answer, but another way is with 'echo'. Start by typing 'echo "' with one quotation mark (") and then hitting enter. You can then type lines and hit enter. On the final line, type the closing quotation mark (") and then the greater-than (>) and the desired file name.

echo "
> from __future__ import braces
> import antigravity" > foo.py

نصائح أخرى

What about using echo? I'd do this if I were to create/append to a file with a single line in a hurry:

$ echo "The world is a weird, mysterious place." >> ~/diary

If there is more than one line, I use cat or my favorite editor:

$ cat >> ~/diary
The world is a weird, mysterious place.
I ran the command man ascii and was delighted.^D
$

A lot of times I copy script code from the net, paste it in an empty vim buffer /tmp/test.sh or similar, maybe indent it with gg=G and then work on it.

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.

if i wont open it right away i do:

touch ./filename.txt
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top