2012-09-19 29 views
8

Im değişkenin içeriği olan bir dosyayı yazmaya çalışıyorum, ama mevcut doesnt dosya oluşturun eğer:aksi bash oluşturmak Varlığından eğer eklemek, bir dosya yazma

:

Şimdiye kadar ben bu var

echo "$Logstring" >> $fileLog 

Dosyada eksik olduğu için eksik bir hata var. Bir koşul gerekli midir?

+7

?' >> 'yönlendirme operatörü Eğer mevcut değilse dosyayı yaratacaktır – chrisaycock

+4

Ana dizin var mı? – nneonneo

+2

Belki de '$ fileLog' bir boşluk içeriyor - bu, eğlenceyi mahvetmesini önlemek için çift tırnak içine alın. –

cevap

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 

dirname için dosyanın klasör adı boşluk varsa ihtiyaç vardır "kaçmış. Eğer alıyorsanız hangi hata

İlgili konular