Zhen Liu
Zhen Liu

Reputation: 7932

Create file with content in one line of bash

I wish to create a single file with some contents known to me.

How do I do this in couple lines of bash?

this command will be used inside of a single script, so it should create file, add text, save, and quit automatically by itself without human intervention.

I know that

cat >> some.text
type some stuff
ctrl + D

will work. But is there a pure command line way of doing it?

Thanks

Upvotes: 10

Views: 20194

Answers (5)

Andreas Haferburg
Andreas Haferburg

Reputation: 5520

If you need sudo to write the file, sudo echo "text" > file won't work.

Use this to overwrite the file

echo "text" | sudo tee file > /dev/null

and this to append:

echo "text" | sudo tee --append file > /dev/null

Taken from here.

Upvotes: 2

Joel Gray
Joel Gray

Reputation: 319

Great answer from @that-other-guy, also important to note that you can include the directory of the file in there and not to forget your bin/bash stuff at the start, and that it works for more than just text files. See below my example for yaml files. And remember to make your bash files executable after with: chmod u+x fileName.sh

#!/usr/bin/bash

cat >> ~/dir/newDir/yamlFiles/testing.yaml << 'END'
service:
  - testing
testing:
  setOpts:
    podCount: 2
END

Upvotes: 1

mrks
mrks

Reputation: 53

For making it multiline its also possilbe to echo in "execution mode":

echo -e "line1\nline2" > /tmp/file

so the \n will make a carriage return.

Upvotes: 4

Jacob
Jacob

Reputation: 940

You could also do the following: echo 'some stuff' > your/file.txt

For multiline, here's another example: printf "some stuff\nmore stuff" >> your/file.txt

Upvotes: 10

that other guy
that other guy

Reputation: 123570

Use a "here document":

cat >> some.text << 'END'
some stuff here
more stuff
END

The delimiter (here END) is an arbitrary word. Quoting this delimiter after the << will ensure that no expansion is performed on the contents.

Upvotes: 15

Related Questions