In the middle of a shell script, I need to create a file with some specific content. How do I do it? Can it be done using cat
?

- 333,661

- 125
- 2
- 8
-
2What is this file you are trying to create and what should be its contents? Provide some more information! – Inian Mar 26 '18 at 06:10
2 Answers
It can be done with cat
and a here-document:
cat >outfilename <<END_FILE
this is the contents of the file
la-di-da!
END_FILE
The here-document is what's between the <<END_FILE
and the corresponding END_FILE
at the end. The ending END_FILE
must be the only word on that line and must be placed at the start of the line. The word END_FILE
may be any word (e.g. END_CONFIG_FILE
or WHEN_WILL_SUMMER_COME
or whatever makes sense).
Variables will be expanded in the document. If this is not wanted, then quote the first here-document delimitier:
cat >outputfilename <<'MY_DOC'
another here document thingy
The $PATH variable will not be expanded here
MY_DOC
A here-document is technically a redirection and in the examples above we redirect it into the cat
command. The cat
command the passes it on to the named file using a standard output redirection.
See also questions tagged with here-document on this site.
From comments: "I get Permission denied and sudo
doesn't help"
Yes, if you don't have write permissions in the directory, you can't redirect to the output file. Also, the creation of the output file happens before sudo
is even called, so using sudo
won't help.
You could do
sudo tee outputfilename >/dev/null <<MY_DOC
contents of file
goes here
MY_DOC
This will run tee
as root and tee
will create outputfilename
in the current directory (as root). The redirection to /dev/null
is to stop tee
from also outputting the document to the terminal.
The tee
command copies its input to all files named on its command line, and to the standard output (the terminal if not piped to another command).

- 333,661
-
The above command is returning the error -bash: outfilename: Permission denied. Tried sudo too – Sampad Mund Mar 26 '18 at 07:26
-
@SampadMund That's because you don't have permission to write in the current directory. Using
sudo
will not help since the redirection is not part of the command thatsudo
executes. Instead, usesudo tee outputfilename >/dev/null <<MY_DOC
etc. – Kusalananda Mar 26 '18 at 07:36
For arbitrary (not necessarily text) content, you can use uudecode
:
uudecode << "EOF" | gunzip > some-file
begin 644 -
M'XL(``S*N%H``ZMW]7%C8F1D@`%F!CL&$.]"&(3O`!7W8&>"JW%@L&#@!)*R
M##(,;$`^*Y(Z=/H'(RK-`;>'@8$%B"V@QJ+3,@RH-",2S<J`&[QXPHA",S`H
MP/6!W#KA,T1\PF=%%+I""**Z0)4!11\35-^-OQ!]-_XJHM`?H-9\0/,?"Q2'
M0/V#3KLPH-(L4#K@:4D*B+U@/<1`=+H%:@&,AND+!.ICPP@-W$``2@=\
M[=_WM][)]>H;RT_=,CYV2[F?)CE^9;*KC]Z\Z+M0?=:LTM[C#Q(T97MD&/``
C?Z"GA;"('V?"+OX1A[@'(W;Q<&;LXINAY@``J665NN@#````
`
end
EOF
Where that output (in the sample above the first 1000 bytes of /bin/ls
on my system) is generated with gzip < file | uuencode -
.

- 544,893