在bash中写入一个文件,如果文件存在则追加内容,否则创建新文件。

17

我尝试将一个变量的内容写入文件,但如果文件不存在则创建它:

到目前为止,我得到了以下代码:

echo "$Logstring" >> $fileLog

当文件不存在时,我缺少什么?为什么会报错?是否需要if条件语句?


11
你遇到了什么错误?>> 重定向操作符会在文件不存在时创建它。 - chrisaycock
5
父级目录存在吗? - nneonneo
2
也许 $fileLog 包含一个空格 - 用双引号将其包裹起来,以防止它破坏乐趣。 - Ben Graham
2个回答

20

使用touch命令:

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

1
补充上面的评论,我不得不查找这个问题,所以认为值得分享。如果您想将ssh密钥推送到多台服务器等情况下,触碰已经存在的文件只会更新最后修改日期戳,因此这是一个好答案。 - Tim Hamilton
这个解决方案足以处理那些文件夹肯定存在的情况,例如容器内的某个项目根目录。 - Николай Конев
1
很遗憾,这个解决方案并不实用。如果文件不存在但其目录存在,则echo "string" >> file本身就可以正常工作。我们需要一种方法来创建文件和一个或多个父目录,而这里touch失败了。至少我的touche来自GNU coreutils 8.28。 - tanius
1
在这种情况下,您要寻找的是 mkdir -p $(basename $fileLog)。首先执行此操作以确保文件夹存在,然后像上面那样触摸文件,最后继续流式传输到该文件。 - user2085368

6
   #! /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 中的双引号。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接