2.1.4 Linux编程常用命令及工具(3)
8.重定向操作
在编程调试时,重定向操作对存储可执行文件的输出结果有很大帮助,特别是在需要逐行分析输出结果的时候。重定向操作是将标准的输入输出设备重新定位到某个文件中。
标准输入设备:默认为键盘,其文件描述符为0(关于描述符内容在文件管理章节将详细介绍)。
标准输出设备:默认为显示器,其文件描述符为1。
标准错误输出设备:默认为显示器,其文件描述符为2。
以下列出了部分常见的重定向操作实例。
(1)cat<test01:将输入重定向到test01文件,此命令得以正常运行的条件是test01文件存在。示例如下:
[root@localhost ~]# cat test01//显示test01文件内容 hello world test01 [root@localhost ~]# cat<test01 //将输入 重定向到test01文件,即将test01文件内容作为输 //入信息 hello world test01 |
(2)cat>test02<test01:将标准的正确输出重定向到test02文件,将输入设备重定向到test01文件。要求test01文件存在。如果test02文件存在,将覆盖此文件内容,如果test02文件不存在,将创建此文件。如果test02文件存在,要将输出追加到此文件中应使用"cat>>test02<test01"命令。示例如下:
[root@localhost ~]# cat test01 //显示test01文件内容 hello world test01 [root@localhost ~]# ls -l test02 //查看test02文件是否存在 ls: test02: No such file or directory //不存在,故在后面命令中将创建此文件 [root@localhost ~]# cat>test02<test01 //输入重定向文件test01,输出重定向test02文件 [root@localhost ~]# cat test02 //查看test02文件内容,与test01输出内容一致 hello world test01 |
(3)cat>test02 2>error <test01:将标准的正确输出重定向到test02文件(如果test02文件存在,将被覆盖,追加需要使用"cat>>test02"命令。如果此文件不存在,将被创建),将错误输出重新定向到error文件(如果error文件存在,将被覆盖,追加需要使用"2>>error"命令。如果此文件不存在,将被创建),将输入设备重定向到test01文件。
如果test01文件存在,示例如下:
[root@localhost ~]# cat test01 //test01文件存在,查看test01内容 hello world test01 [root@localhost ~]# ls test02 error //查看当前文件夹是否存在error和test02文件 ls: test02: No such file or directory //不存在 ls: error: No such file or directory //不存在 [root@localhost ~]# cat>test02 2>error<test01//重定向 [root@localhost ~]# cat test02 //因为test01存在,所以test02内容与test01一致 hello world test01 [root@localhost ~]# cat error //将创建此文件,但无内容
|
如果test01文件不存在,示例如下:
[root@localhost ~]# ls test01 test02 error //查看3 个文件是否存在,此处假定文件不存在 ls: test01: No such file or directory //不存在 ls: test02: No such file or directory //不存在 ls: error: No such file or directory //不存在 [root@localhost ~]# cat>test02 2>error<test01 //重定向设置 [root@localhost ~]# cat test02 //因为test01文件 不存在,因此没有输入,test02将为空 [root@localhost ~]# cat error //错误信息存储在此文件中 -bash: test01: No such file or directory //显示错误信息 |
(4)cat>test02 1&2 <test01:&符号表示联合,此命令将正确信息输出重定向到test02文件,2与1联合,错误信息同样输出到test02中。因此,不管test01文件是否存在,相应信息都将输出到test02文件中。
(5)cat 1&2 1>test02<test01:此命令与(4)不一致的地方在于先进行联合,再对标准正确信息输出设备重定向。首先将1和2联合,其实1和2都将为显示器设置,然后再将1(标准正确输出设备)重新定向到文件test02,由于联合没有传递性,标准错误输出设备仍然是显示器,因此,此命令的输入为test01文件,正确信息输出到test02文件,错误信息输出到显示器。
9.常用键盘组合键命令
在进行程序开发和设计时,经常会用到部分键盘组合键,常用的组合键盘命令如下。
^C:<Ctrl+c>中断程序。
^\:<Ctrl+\>退出程序。
^S:<Ctrl+S>结束程序。
^Z:<Ctrl+Z>挂起程序。
部分其他命令可以使用以下命令查看:
[root@localhost ~]# stty -a //键盘组合命令, 实为键盘中断信号,见第8章信号 speed 38400 baud; rows 27; columns 90; line = 0; //^C表示ctrl+c intr = ^C; quit = ^\; erase = ^ ; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0; …… |