重定向一览
时间:2005-12-01 来源:xktop
文件描述符:
标准输入:0;标准输出:1;标准错误:2;
重定向符:
>file:重定向标准输出到file
<file:从file接受标准输入
>>file:重定向标准输出到file,如果file存在则附加输出到file
>|file:即使设置了noclobber仍强制标准输出到file
<>file:file同时作为标准输入与标准输出
<<label:here-document,以shell为标准输入,即屏幕输入为标准输入,直至独到含有label的行
e.g.
xk@linux:~/work> cat >>a.sh<<eof
> this is the test text
> for <<
> eof
xk@linux:~/work> cat a.sh
this is the test text
for <<
xk@linux:~/work>
n>file:将文件描述符n重定向到file
e.g.
xk@linux:~/work> cat s.sh
#!/bin/bash
PS3="which is your hobby? Please select:"
OPTIONS="computer:music:math:art"
OIFS=$IFS
IFS=:
select selected in $OPTIONS;do
case $selected in
computer) echo "you select 1";;
music) echo "you select 2";;
math) echo "you select math";;
art) echo "you select art";;
*) echo "error";exit 1;;
esac
done
xk@linux:~/work> ./s.sh 1>out 2>error
3
6
xk@linux:~/work> cat out
you select math
error
xk@linux:~/work> cat error
1) computer
2) music
3) math
4) art
which is your hobby? Please select:which is your hobby? Please select:xk@linux:~/work>
这里也可以看出select的提示信息是通过标准错误输出的。
xk@linux:~/work> lkajdflk 2>out
xk@linux:~/work> cat out
-bash: lkajdflk: command not found
&>file:重定向标准输出和标准错误到file
e.g.
xk@linux:~/work> cat s.sh
#!/bin/bash
PS3="which is your hobby? Please select:"
OPTIONS="computer:music:math:art"
OIFS=$IFS
IFS=:
select selected in $OPTIONS;do
case $selected in
computer) echo "you select 1";;
music) echo "you select 2";;
math) echo "you select math";;
art) echo "you select art";;
*) echo "error";exit 1;;
esac
done
xk@linux:~/work> rm error.bak
xk@linux:~/work> ./s.sh &>error.bak
3
6
xk@linux:~/work> cat error.bak
1) computer
2) music
3) math
4) art
which is your hobby? Please select:you select math
which is your hobby? Please select:error
xk@linux:~/work>
n>&m:将文件描述符n发送到与文件描述符m相同的位置(文件或管道等)
e.g.
xk@linux:~/work> lkjaldskfjlk 2>error 1>out 2>&1
xk@linux:~/work> cat out
-bash: lkjaldskfjlk: command not found
xk@linux:~/work> cat error
xk@linux:~/work>
可见标准错误被以标准输出的形式传出。继续,
xk@linux:~/work> cat out 2>error 1>>out 1>&2
xk@linux:~/work> cat out
-bash: lkjaldskfjlk: command not found
xk@linux:~/work> cat error
-bash: lkjaldskfjlk: command not found
xk@linux:~/work>
这里标准输出又被以标准错误的形式传出。