Reputation: 7932
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
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
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
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
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
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