Linux学习之路-文件输入输出

来源:互联网 发布:怎么向淘宝投诉卖家 编辑:程序博客网 时间:2024/06/05 09:56

Linux的shell文件输出一般采用重定向,将echo重定向到一个文件比如把str变量中的值写到文件中可以直接echo $str>test.txt,当使用>时是覆盖,使用>>时是追加

xiaoxiaobing@xiaoxiaobing-PC:~/Desktop$ str=abcdefg
xiaoxiaobing@xiaoxiaobing-PC:~/Desktop$ echo $str>test.txt
xiaoxiaobing@xiaoxiaobing-PC:~/Desktop$ cat test.txt
abcdefg


读文件可以使用shell的while,把test.txt中的内容一行一行地读出来,并打印到控制台

#!/bin/bash

while read line

do

echo $line

done<test.txt

输出结果:

abcdefg

也可以用cat + while来一行一行地读

#!/bin/bash

cat test.txt|while read line

do

echo $line

done

输出结果:

abcdefg


当然也可以把其他命令的输出重定向到文件中

比如把当前目录下的目录和文件名重定向到test.txt文件中

xiaoxiaobing@xiaoxiaobing-PC:~/Desktop$ cat test.txt
abcdefg
xiaoxiaobing@xiaoxiaobing-PC:~/Desktop$ ls
1506存照2                                                Deep learning  test
6_主要功能和设计界面视频.mp4                             Double-ME      test.sh
book                                                     My Book.zip    test.txt
Caffe官方教程中译本_CaffeCN社区翻译%28caffecn.cn%29.pdf  recover
xiaoxiaobing@xiaoxiaobing-PC:~/Desktop$ ls>test.txt
xiaoxiaobing@xiaoxiaobing-PC:~/Desktop$ cat test.txt
1506存照2
6_主要功能和设计界面视频.mp4
book
Caffe官方教程中译本_CaffeCN社区翻译%28caffecn.cn%29.pdf
Deep learning
Double-ME
My Book.zip
recover
test
test.sh
test.txt

在bash中我们可以重定向9个文件描述符,其中0是标准输出,1是标准输入,2是error输出

比如我们想把错误输出到error.txt文件中

xiaoxiaobing@xiaoxiaobing-PC:~/Desktop$ sh text.sh 2>error.txt

用cat来看一下error.txt文件中是否已经保存了刚才的error信息

sh: text.sh: 没有那个文件或目录

结果显示已经把error信息保存到了error.txt中了


原创粉丝点击