2012-09-19 7 views
8

Nel tentativo di scrivere un file con il contenuto di una variabile, ma se il file doesnt esiste crearla:scrivere un file, aggiungere se esiste altro modo di creare in bash

Finora ho ottenuto questo:

echo "$Logstring" >> $fileLog 

Ciò che mi manca perché quando il file non esiste c'è un errore. È necessaria una condizione if?

+7

Quale errore vuoi arrivare? L'>>' 'operatore di redirezione creerà il file se non esiste. – chrisaycock

+4

Esiste la directory principale? – nneonneo

+2

Forse '$ fileLog' contiene uno spazio - avvolgilo tra virgolette doppie per evitare che ciò rovini il divertimento. –

risposta

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

la sfuggito "per nomedir sono necessari se la cartella di file ha gli spazi nel nome.