17

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?

coolerking
  • 501
  • 1
  • 5
  • 13

2 Answers2

20

Use the touch command:

touch $fileLog
echo "$Logstring" >> $fileLog
Igor Dvorzhak
  • 4,360
  • 3
  • 17
  • 31
user2085368
  • 695
  • 6
  • 11
  • 1
    To add to the above comment, I had to look this up so thought it might be worth sharing, touching a file that already exists will only update the last-modified date stamp, so this is a good answer if you're looking to push out your ssh keys to a number of servers, etc. – Tim Hamilton Apr 12 '19 at 00:43
  • This solution is enough for cases where folder does exist for sure, i.e. some project root inside a container. – Николай Конев Aug 22 '19 at 10:00
  • 1
    Sadly, this solution is not useful. `echo "string" >> file` works fine by itself if the file does not exist yet but *its directory exists*. We need a way to create the file incl. one or more parent directories, and here `touch` fails. At least my `touch`, from GNU coreutils 8.28. – tanius Sep 24 '19 at 17:45
  • 1
    @tanius in that case, you're looking for `mkdir -p $(basename $fileLog)` . Do that first, to ensure the folder exists, touch the file as above, and then proceed to stream to it. – user2085368 Nov 30 '21 at 07:12
6
   #! /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.