to create or append to a file in bash
, you can use >>
.
echo "sample text" >> sample_file
echo "append text" >> sample_file
Question
Very simple task: grab an output and redirect it to a file, using shell.
Now, I need to create the file if it does not exist, or if it exist, I need to append data
If I use output > file.txt
I get data overwritten at each access. Not what I want.
If I use output >> file.txt
I get an error, because shell is trying to access the file while, I need it to create it first (it does not exist yet).
Is there a way to say in one line to create it, if the file doesn't exist, and append data or append only if the file does exist already?
I can just do that using an if-else (if file exist use >> otherwise use >), and I would like to avoid to complicate my code, if there is an easier way.
Solution
to create or append to a file in bash
, you can use >>
.
echo "sample text" >> sample_file
echo "append text" >> sample_file