2012-09-19 12 views
8

Im próby zapisu pliku z zawartością zmiennej, ale jeśli plik nie robi istnieć go utworzyć:zapisać plik, dołącz jeśli istnieje inny sposób stworzyć w bash

Do tej pory mam to:

echo "$Logstring" >> $fileLog 

Co im brakuje, ponieważ gdy plik nie istnieje tam jest błąd. Czy warunek jeśli jest konieczny?

+7

Co błędzie jest wyświetlany? Opcja' '>> operator przekierowania utworzy plik, jeśli nie istnieje – chrisaycock

+4

Czy istnieje katalog nadrzędny? – nneonneo

+2

Być może '$ plikLog' zawiera spację - owinąć go w podwójne cudzysłowy, aby zapobiec rujnowaniu zabawy. –

Odpowiedz

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 

uciekł "na dirname są potrzebne, jeśli folder pliku zawiera spacje w nazwie.

Powiązane problemy