快速入门Shell编程(五)输入输出重定向

网友投稿 500 2022-05-29

重定向作用

一个进程默认会打开标准输入、标准输出、错误输出三个文件描述符。

重定向可以让我们的程序的标准输出、错误输出的信息重定向文件里,那么这里还可以将文件的内容代替键盘作为一种标准输入的方式。

重定向符号

输入重定向符号"<"

输出重定向符号">",">>","2>","&>"

输入重定向功能

会把文件的内容当做参数输入到进程,如下例子:

[root@omp120 home]# cat file.txt hello [root@omp120 home]# read a < file.txt [root@omp120 home]# echo $a hello

1

2

3

4

5

file.txt文件的内容是hello,上述的例子就是把file.txt的内容重定向到a这个变量,并把a变量打印出来。

输出重定向功能

会把文件内容清空,在把输出内容重定向到指定的文件里,并且如果文件不存在则创建,如下例子:

[root@lincoding tmp]# echo 123 > /tmp/test [root@lincoding tmp]# cat /tmp/test 123 [root@lincoding tmp]# echo abc > /tmp/test [root@lincoding tmp]# cat /tmp/test abc

1

2

3

4

5

6

会把输出的内容追加到指定的文件里,该文件不会被清空,并且如果文件不存在则创建,如下例子:

[root@lincoding tmp]# echo 123 >> /tmp/test [root@lincoding tmp]# cat /tmp/test 123 [root@lincoding tmp]# echo abc >> /tmp/test [root@lincoding tmp]# cat /tmp/test 123 abc

1

2

3

4

5

6

7

是把进程错误输出的内容重定向到指定的文件里,如下例子:

[root@lincoding home]# abc -bash: abc: command not found [root@lincoding home]# abc > error.txt -bash: abc: command not found [root@lincoding home]# cat error.txt [root@lincoding home]# [root@lincoding home]# abc 2> error.txt [root@lincoding home]# cat error.txt -bash: abc: command not found

1

2

3

4

5

6

7

8

9

以上的演示结果可以得知,abc不是Linux的命令,执行了会报错说abd命令未找到的错误信息输出,那么这个错误信息需要用2>重定向符才能把进程错误输出的内容重定向到指定的文件。

无论进程输出的信息是正确还是错误的信息,都会重定向到指定的文件里,如下例子:

[root@lincoding home]# abc &> file.txt [root@lincoding home]# cat file.txt -bash: abc: command not found [root@lincoding home]# free -m &> file.txt [root@lincoding home]# cat file.txt total used free shared buffers cached Mem: 980 918 62 0 71 547 -/+ buffers/cache: 299 681 Swap: 1983 0 1983

1

2

3

4

5

6

7

8

9

输入重定向和输出重定向组合使用

输入和输出也是可以组合使用的,那么这个组合主要应用于在Shell脚本当中产生新的配置文件的场景,如下Shell脚本例子:

#!/bin/bash cat > /home/a.sh << EOF echo "hello bash" EOF

1

2

3

4

把cat命令的输出重定向到/root/a.sh脚本文件,并且用输入重定向把EOF为脚本结尾。那么通过执行这个脚本,就会产生一个内容为echo "hello bash"文件名为a.sh的脚本文件。

执行结果:

[root@lincoding home]# ./test.sh [root@lincoding home]# ls -l a.sh -rw-r--r--. 1 root root 18 Sep 27 16:41 a.sh [root@lincoding home]# chmod u+x a.sh [root@lincoding home]# cat a.sh echo "hello bash" [root@lincoding home]# ./a.sh hello bash

1

2

3

4

5

6

7

8

快速入门Shell编程(五)输入输出重定向

小结

以上的内容就是关于输入和输出重定向的用法,那么大家要注意输出重定向包括覆盖和追加模式,无论是覆盖还是追加模式,尽量不要用于我们的系统配置文件,那么在应用之前大家要注意对系统文件进行备份。

输入和输出重定向,还可以组合使用,一般在Shell脚本当中去产生新的配置文件的时候,会用到它们的组合的方式。

Shell 任务调度

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:MapReduce Service转售版本学习材料
下一篇:Android中的Serializable、Parcelable
相关文章