Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write a file, append if it exists otherwise create in bash

Tags:

bash

append

echo

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?

like image 880
coolerking Avatar asked Sep 19 '12 21:09

coolerking


People also ask

Does append create a file if it doesn't exist?

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.

How do I append to a file in bash?

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.

How do I overwrite a shell 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.


2 Answers

Use the touch command:

touch $fileLog
echo "$Logstring" >> $fileLog
like image 70
user2085368 Avatar answered Oct 27 '22 09:10

user2085368


   #! /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.

like image 44
Ярослав Рахматуллин Avatar answered Oct 27 '22 10:10

Ярослав Рахматуллин