Linuxshell
必需要知道一个东西:Linux系统将每一个对象看成文件处理,输入输出对象也是如此。bash
Linux 标准文件描述符:this
文件描述符 | 缩写 | 描述 |
0 | STDIN | 标准输入 |
1 | STDOUT | 标准输出 |
2 | STDERR | 标准错误 |
解释,对终端接口,标准输入是键盘。不少bash命令经过STDIN接受输入,eg,cat命令 cat>testcat 将接受的输入重定向到testcat文件。对终端接口:标准输出是终端监视器。,eg ,ls -l > testls 将标准输出重订向到testls文件。STDERR,表述shell处理运行错误,运行脚本时,对这种错误实际上是很关注的,记录下来颇有用。spa
使用shell 的时候 ">"表示输出重定向,1>,2>两种组合,就是对标准输出,和错误输出两种的区别。code
[root@iZ28npved5eZ tmp]# ls -l test sad//不区分的时候 ls: cannot access sad: No such file or directory -rwxr--r-- 1 root root 49 May 3 10:19 test
对标准输出进行重定向:对象
ls -l test sad 1>tets ls: cannot access sad: No such file or directory
对标准错误进行重定向:接口
ls -l test sad 2>tets -rwxr--r-- 1 root root 49 May 3 10:19 test
热身结束了,在脚本中重定向来了。
ip
临时重定向:table
[root@iZ28npved5eZ tmp]# cat test #!/bin/bash #this is stderr echo "this is error" >&2 //标记成标准错误 echo "this is sucess" //使用 [root@iZ28npved5eZ tmp]# ./test 2>error this is sucess //标准错误就被定向到error文件中,之因此称为临时重定向在与 ./test 2>error 能够任意修改为 ./test 1>sucess 这样又是另一种结果了。
永久重定向:class
cat test #!/bin/bash #this is stderr exec 1>sucess //将标准输出重定向到sucess文件 echo "this is error" >&2 echo "this is sucess" //使用 ./test this is error
更复杂一点的就是多种重定向在一个脚本中同时存在,就须要,本身注意永久重定向所申明的位置。(也能够本身定义重定向文件描述符)
文件重定向输入(其实和管道用处很类似,将某个文件的内容当标准输入重定向进来)
cat test #!/bin/bash #this is stderr exec 0<script //将script文件内容当标准输入重定向进来 while read line do echo $line done //用法 ./test { grep -c $1 chen }
还有一些比较偏的用法:禁止命令输入:重定向到 /dev/null 文件就会直接把定向的所有丢弃。