bash写入文件write

本文概述

  • 方法1:仅将输出写入文件
  • 方法2:正常打印输出并将其写入文件
当我们在bash shell中运行任何命令时,通常会将该命令的输出打印到终端,以便我们可以立即读取它。但是bash还提供了一个选项,可以将任何bash命令的输出“重定向”到日志文件。它可以将输出保存到文本文件中,以便我们以后在需要时可以对其进行查看。
方法1:仅将输出写入文件要将Bash命令的输出写入文件,我们可以使用直角括号符号(> )或双直角符号(> > ):
直角括号标志(> )
它用于将bash命令的输出写入磁盘文件。如果没有具有指定名称的文件,则它将创建一个具有相同名称的新文件。如果文件具有指定名称,则文件内容将被覆盖。
双直角标志(> > )
它用于将bash命令的输出写入文件,并将输出附加到文件的现有内容。如果文件不存在,它将使用指定的名称创建一个新文件。
从技术上讲,这两个操作符都将“ stdout(标准输出)”重定向到文件。
以一种简单的方式,当我们第一次写入文件并且不希望以前的数据出现在文件中时,我们应该使用直角括号符号(> )。如果文件中已经存在内容,它将覆盖内容。在进一步的脚本中,我们可以使用双直角符号(> > )将数据附加到文件中。

‘ ls’ 命令用于打印当前目录中存在的所有文件和文件夹。但是,当我们运行带有直角括号符号(> )的’ ls’ 命令时,它将不会在屏幕上打印文件和文件夹列表。它将输出保存到我??们指定的文件中,即如下所示:
Bash脚本
#!/bin/bash #Script to write the output into a file#Create output file, override if already present output=output_file.txt#Write data to a file ls > $output#Checking the content of the file gedit output_file.txt

输出量
bash写入文件write

文章图片
如此处所示,“ ls”命令的输出重定向到文件中。要将文件的内容打印到终端,我们可以使用以下格式的“ cat”命令:
Bash脚本
#!/bin/bash #Script to write the output into a file#Create output file, override if already present output=output_file.txt#Write data to a file ls > $output#Printing the content of the file cat $output

输出量
bash写入文件write

文章图片
如果要在不删除可用数据的情况下将多个命令的输出重定向到单个文件,则可以使用> > 运算符。假设我们要将系统信息附加到指定的文件,我们可以通过以下方式进行操作:
Bash脚本
#!/bin/bash #Script to write the output into a file#Create output file, override if already present output=output_file.txt#Write data to a file ls > $output#Appending the system information uname -a >> $output#Checking the content of the file gedit output_file.txt

输出量
bash写入文件write

文章图片
在这里,第二条命令的结果将附加到文件末尾。
我们可以重复几次此过程,以将输出追加到文件末尾。
方法2:正常打印输出并将其写入文件某些人可能不喜欢使用> 或> > 运算符将输出写入文件,因为终端中将没有命令的输出。这就是为什么使用“ tee”命令的原因。 ‘ tee’ 命令用于将接收到的输入打印到屏幕上。它可以同时将输出保存到文件中。
Bash脚本
#!/bin/bash #Script to write the output into a file#Create output file, override if already present output=output_file.txt#Write data to a file ls | tee $output

输出量
bash写入文件write

文章图片
就像> 运算符一样,这??将覆盖文件的内容,但也会在屏幕上打印输出。
如果要在不使用tee命令删除文件内容的情况下将输出写入文件,则可以使用以下形式将输出打印到终端:
Bash脚本
#!/bin/bash #Script to write the output into a file#Create output file, override if already present output=output_file.txtecho "< < < List of Files and Folders>>>" | tee -a $output #Write data to a file ls | tee $outputecho | tee -a $output #Append System Information to the file echo "< < < OS Name>>>" | tee -a $output uname | tee -a $output

输出量
bash写入文件write

文章图片
【bash写入文件write】这不仅将输出附加到文件末尾,而且还将输出打印在屏幕上。

    推荐阅读