输入输出重定向

>, < 表示数据的流动方向,比如

command < inputfile  #表示把 inputfile 中的内容作为标准输入(STDIN)提供给 command
command > outputfile #表示把 command 产生的标准输出(STDOUT)导进 outputfile 中保存。如果 outputfile 不存在,就自动创建,如果已存在,就擦除旧内容然后写入。

>> 表示向文件中追加数据

command >> outputfile #会把 command 产生的标准输出 ( STDOUT ) 导进 outputfile, 追加到 outputfile 已有的内容后面。

<< 表示内联输入重定向(inline input redirection),需要一个文本标记来划分输入数据的开始和结尾,“文本标记”可以是任何字符串,只要开始和结束保持一致即可,如下所示。

command << input #这里 input 就是“文本标记”,此后的内容就是输入,导向标准输入(STDIN)
xxxxx
xxxxx
xxxxx
input # 结束重定向

| 表示管道

command1 | command2 # command1 每产生一行标准输出 (STDOUT),立即重定向,作为输出流向 command2
ls | sort | more # ls 的结果重定向给 sort,然后给 moremore 显示第一页结果,如果需要更多结果则往下滚动。

 文件描述符:linux将输入输出进程也当做文件对象处理,用文件描述符标识文件对象,非负整数,每个进程最多9个文件描述符

0  STDIN

1  STDOUT

2  STDERR

ls test badtest test2 2> test5 # 将 STDERR 重定向至文件 test5,注意 2> 两个符号之间不能有空格
ls test badtest test2 &> test7 # 将所有输出,即 STDOUT, STDERR 都重定向到文件 test7
echo "This is an error" >&2    # 将信息重定向至 2 指定的文件(也可能是屏幕)
exec 1>testout                     #  exec命令会启动一个新shell来将脚本中这一行以后 1 的所有输出都重定向到 testout

还可以通过轮换来交换不同描述符指向的文件对象

exec 3>&1                # 3 重定向至显示器
exec 1>test14out        # 1 重定向至文件 test14out
echo "This should store in the output file"   #这两行都进了 test14out
echo "along with this line."
exec 1>&3    # 1 重定向至显示器
echo "Now things should be back to normal"    #这行出现在显示器

上面相当于用描述符 3 储存了显示器位置,方便 1 回来浪完了回来重新指向显示器。

类似地,可以将 0 指向文件,然后再回到键盘。

exec 6<&0       # 6 指向键盘  

exec 0< testfile # 0 指向文件 testfile,testfile 的内容重定向至 STDIN

count=1
while read line
do
    echo "Line #$count: $line"
    count=$[ $count + 1 ]
done
exec 0<&6        # 0 指向键盘,键盘输入 STDIN 
read -p "Are you done now?" answer
case $answer in
Y|y) echo "Goodbye";;
N|n) echo "Sorry, this is the end.";;
esac

还有些更复杂的操作,暂时用不到,先不写了