写一个文件,如果存在则追加,否则在 bash 中创建

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12503357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:19:12  来源:igfitidea点击:

write a file, append if it exists otherwise create in bash

bashappendecho

提问by coolerking

Im trying to write a file with the content of a variable, but if the file doesnt exist create it:

我试图用变量的内容编写一个文件,但如果该文件不存在,请创建它:

So far i got this:

到目前为止,我得到了这个:

echo "$Logstring" >> $fileLog

What im missing because when the file doesnt exist theres an error. Is an if condition necessary?

我缺少什么,因为当文件不存在时会出现错误。if 条件是否必要?

采纳答案by Ярослав Рахматуллин

   #! /bin/bash
   VAR="something to put in a file"
   OUT=
   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


the escaped " for dirname are needed if the folder of file has spaces in the name.

如果文件的文件夹名称中有空格,则需要转义的 " 用于 dirname。

回答by user2085368

Use the touchcommand:

使用touch命令:

touch $fileLog
echo "$Logstring" >> $fileLog