shell脚本学习第四弹-管道与IO重定向
一、IO介绍
什么是IO?简单的来说,IO就是输入输出;在unix里面,我们必须要标准输入,标准输出和标准错误。我们可以用程序运行过程来更明显说明:程序的输入就是标准输入,程序处理完之后,输出结果就是标准输出,或者报错就是标准错误。
在shell编程里面,我们用cat命令就可以很好的解释这个标准输入和标准输出,请看案例:
shell$ cat
cd
cd
vf
vf
bg
bg
^C
很显然,我们输入什么,就会相应的输出来。
二、管道
顾名思义,管道就像我们在生活中见到的管道是一样的,只不过我们这里是虚拟的,我们的管道就是一个管道和一个管道相连,也就是可以这么说,上一个管道的出口就是下一个管道的入口,这么精简的回答很容易懂了吧。
在shell编程中,管道的表示方法是“|”,我们经常在命令中用到,比如:
$ cat point_num.c | grep -n "include" 1:#include<stdio.h> 2:#include<stdlib.h> 3:#include<string.h>
这就是管道的一种使用方法。
注意:我们在使用管道的时候,尽可能的把减少数据量的操作放在前面,因为管道的数据共享是在linux内核中通过拷贝实现的,减少数据量可以很大程度上提高效率。
三、重定向
重定向就是把标准输出和标准输入改写到某个特定的文件或者设备中。
1.用 > 来改变标准输出
command > file 将command的标准输出重定向到文件中,而不是打印在终端上。
C$ cat point_num.c > 1.txt
C$ cat 1.txt
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int num = 10;
char* buf = malloc(10);
memset(buf,0,10);
// char *buf = NULL;
char* str = "hello";
printf("%p\n",buf);
memcpy(buf+1,str,10);
printf("%p\n",buf+1);
printf("%s\n",buf+1);
free(buf);
}
我们会发现结果保存在了1.txt文件中。
2.用 < 来改变标准输入
command < file 将command的标准输入重定向到文件
案例:
/C$ cat < struct.c > 1.txt
/C$ cat 1.txt
#include<stdio.h>
void Print()
{
printf("hello 000\n");
}
struct Test
{
void (*Print)();
};
int main()
{
struct Test test;
test.Print = Print;
test.Print();
return 0;
}
所以,我们会发现把struct.c的文件存到了1.txt文件中,而且1.txt中原来的数据不见了。
3.追加文件
command >> file 将command的追加到到文件的末尾
案例:
/C$ cat point_num.c >> 1.txt
/C$ cat 1.txt
#include<stdio.h>
void Print()
{
printf("hello 000\n");
}
struct Test
{
void (*Print)();
};
int main()
{
struct Test test;
test.Print = Print;
test.Print();
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int num = 10;
char* buf = malloc(10);
memset(buf,0,10);
// char *buf = NULL;
char* str = "hello";
printf("%p\n",buf);
memcpy(buf+1,str,10);
printf("%p\n",buf+1);
printf("%s\n",buf+1);
free(buf);
}
我们会发现这个文件追加到了1.txt后面。
欢迎大家关注微信公众号:技术修炼之路,更多干货等你来拿。