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.
You can use the cat command to append data or text to a file. The cat command can also append binary data. The main purpose of the cat command is to display data on screen (stdout) or concatenate files under Linux or Unix like operating systems.
In Linux, to write text to a file, use the > and >> redirection operators or the tee command.
The short answer:
echo "some data for the file" >> fileName
However, echo
doesn't deal with end of line characters (EOFs) in an ideal way. So, if you're gonna append more than one line, do it with printf
:
printf "some data for the file\nAnd a new line" >> fileName
The >>
and >
operators are very useful for redirecting output of commands, they work with multiple other bash commands.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With