2012-09-19 18 views
8

इम एक चर की सामग्री के साथ एक फ़ाइल में लिखने का प्रयास है, लेकिन अगर फ़ाइल does not मौजूद इसे बनाने:एक फ़ाइल में लिखने, संलग्न अगर यह अन्यथा पार्टी में बना मौजूद

: अब तक

मैं यह मिल गया

echo "$Logstring" >> $fileLog 

मुझे क्या याद आ रही है क्योंकि जब फ़ाइल मौजूद नहीं है तो कोई त्रुटि होती है। अगर एक शर्त आवश्यक है?

+7

क्या त्रुटि मिल रहा है?' '>> पुनर्निर्देशन ऑपरेटर अगर यह अस्तित्व में नहीं है तो फ़ाइल बनायेगी। – chrisaycock

+4

क्या मूल निर्देशिका मौजूद है? – nneonneo

+2

शायद '$ fileLog' में एक स्पेस है - इसे मज़े को बर्बाद करने से रोकने के लिए इसे डबल कोटेशन अंक में लपेटें। –

उत्तर

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 के लिए करता है, तो फ़ाइल के फ़ोल्डर नाम में रिक्त स्थान है की जरूरत है।

संबंधित मुद्दे