Im trying to write a file with the content of a variable, but if the file doesnt exist create it:
So far i got this:
echo "$Logstring" >> $fileLog
What im missing because when the file doesnt exist theres an error. Is an if condition necessary?
Append mode adds information to an existing file, placing the pointer at the end. If a file does not exist, append mode creates the file. Note: The key difference between write and append modes is that append does not clear a file's contents.
To make a new file in Bash, you normally use > for redirection, but to append to an existing file, you would use >> . Take a look at the examples below to see how it works. To append some text to the end of a file, you can use echo and redirect the output to be appended to a file.
Even when you use the yes command, the shell will still prompt you to confirm the overwrite. The best way to force the overwrite is to use a backward slash before the cp command as shown in the following example. Here, we are copying contents of the bin directory to test directory.
Use the touch
command:
touch $fileLog
echo "$Logstring" >> $fileLog
#! /bin/bash
VAR="something to put in a file"
OUT=$1
if [ ! -f "$OUT" ]; then
mkdir -p "`dirname \"$OUT\"`" 2>/dev/null
fi
echo $VAR >> $OUT
# the important step here is to make sure that the folder for the file exists
# and create it if it does not. It will remain silent if the folder exists.
$ sh out hello/how/are/you/file.out
geee: ~/src/bash/moo
$ sh out hello/how/are/you/file.out
geee: ~/src/bash/moo
$ sh out another/file/lol.hmz
geee: ~/src/bash/moo
$ find .
.
./out
./another
./another/file
./another/file/lol.hmz
./hello
./hello/how
./hello/how/are
./hello/how/are/you
./hello/how/are/you/file.out
geee: ~/src/bash/moo
$ cat ./hello/how/are/you/file.out
something to put in a file
something to put in a file
geee: ~/src/bash/moo
$ cat ./another/file/lol.hmz
something to put in a file
the escaped " for dirname are needed if the folder of file has spaces in the name.
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