How can I write data to a text file automatically by shell scripting in Linux?
I was able to open the file. However, I don't know how to write data to it.
How can I write data to a text file automatically by shell scripting in Linux?
I was able to open the file. However, I don't know how to write data to it.
I like this answer:
but would suggest
cat >> FILE.txt << EOF
if you want just add something to the end of the file without wiping out what is already existsLike this:
For environments where here documents are unavailable (
Makefile
,Dockerfile
, etc) you can often useprintf
for a reasonably legible and efficient solution.I know this is a damn old question, but as the OP is about scripting, and for the fact that google brought me here, opening file descriptors for reading and writing at the same time should also be mentioned.
Then
cat
the file on terminalThis example causes file poem.txt to be open for reading and writing on file descriptor 3. It also shows that *nix boxes know more fd's then just stdin, stdout and stderr (fd 0,1,2). It actually holds a lot. Usually the max number of file descriptors the kernel can allocate can be found in
/proc/sys/file-max
or/proc/sys/fs/file-max
but using any fd above 9 is dangerous as it could conflict with fd's used by the shell internally. So don't bother and only use fd's 0-9. If you need more the 9 file descriptors in a bash script you should use a different language anyways :)Anyhow, fd's can be used in a lot of interesting ways.
You can redirect the output of a command to a file:
or append to it
If you want to write directly the command is
echo 'text'