2012-09-19 6 views
8

イムを作成存在する場合は追加し、それを作成して存在してdoesntのファイル場合:、ファイルを書き込み、それはそうでない場合は、変数の内容でファイルを作成しようとbashで

は、これまでのところ、私はこれを得ました

echo "$Logstring" >> $fileLog 

ファイルが存在しないときにエラーが発生するため、何も表示されません。 if条件は必要ですか?

+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のためのファイルのフォルダが名前にスペースが含まれている場合に必要とされている「エスケープ。あなたが取得しているどのようなエラー

関連する問題