bash 如果存在则添加到文件,如果不存在则创建

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1262903/
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-09 18:24:16  来源:igfitidea点击:

Add to file if exists and create if not

bash

提问by Mark Roddy

I am working on a bash script that needs to take a single line and add it to the end of a file if it exists, and if it does not exist create the file with the line.

我正在处理一个 bash 脚本,它需要单行并将其添加到文件的末尾(如果它存在),如果它不存在,则使用该行创建文件。

I have so far:

我到目前为止:

if [ ! -e /path/to/file ]; then
    echo $some_line > /path/to/file
else
    ???
fi

How do I perform the operation that should go in the else (adding the line of text to the existing file)?

如何执行应在 else 中执行的操作(将文本行添加到现有文件中)?

回答by John Millikin

Use two angles: echo $some_line >> /path/to/file

使用两个角度: echo $some_line >> /path/to/file

回答by firstthumb

>creates the file if it doesn't exist; if it exists, overwrites it.

>如果文件不存在,则创建该文件;如果存在,则覆盖它。

>>creates the file if it doesn't exist; if it exists, appends to it.

>>如果文件不存在,则创建该文件;如果存在,则附加到它。

if [ ! -e /path/to/file ]; then
   echo $some_line > /path/to/file
else
   echo $some_line >> /path/to/file
fi