echo "text" >> 'Users/Name/Desktop/TheAccount.txt'
我如何使它在文件不存在时创建它,而在文件已经存在时覆盖它。现在这个脚本只是追加。
echo "text" >> 'Users/Name/Desktop/TheAccount.txt'
我如何使它在文件不存在时创建它,而在文件已经存在时覆盖它。现在这个脚本只是追加。
当前回答
#!/bin/bash
cat <<EOF > SampleFile
Put Some text here
Put some text here
Put some text here
EOF
其他回答
在Bash中,如果你设置了noclobber a la set -o noclobber,那么你使用语法>|
例如:
echo "some text" >| existing_file
如果文件还不存在,也可以这样做
查看是否设置了noclobber: set -o | grep noclobber 关于这种特殊类型的操作符的更详细的解释,请参阅这篇文章 有关重定向操作符的更详尽列表,请参阅这篇文章
要将一个文件的内容覆盖到另一个文件,使用单个大于号,使用两个将追加。
echo "this is foo" > foobar.txt
cat foobar.txt
> this is foo
echo "this is bar" > foobar.txt
cat foobar.txt
> this is bar
echo "this is foo, again" >> foobar.txt
cat foobar.txt
> this is bar
> this is foo, again
正如在其他答案中提到的,如果你有noclobber设置,那么使用>|操作符。
如果您的环境不允许使用>覆盖,请使用管道|和tee,如下所示:
echo "text" | tee 'Users/Name/Desktop/TheAccount.txt'
注意,这也将打印到标准输出。如果不需要,您可以将输出重定向到/dev/null,如下所示:
echo "text" | tee 'Users/Name/Desktop/TheAccount.txt' > /dev/null
#!/bin/bash
cat <<EOF > SampleFile
Put Some text here
Put some text here
Put some text here
EOF
如果你的输出可能有错误,你可能想要使用&号和大于,如下所示:
my_task &> 'Users/Name/Desktop/task_output.log'这将把stderr和stdout重定向到日志文件(而不仅仅是stdout)。