shell如何在脚本中重定向

文章目录

  • 重定向输出
    • 临时重定向【不懂】
    • 永久重定向
  • 重定向输入
  • 创建自己的重定向
    • 创建输出文件描述符
    • 创建输入文件描述符

重定向输出

可以在脚本中用stdout和stderr文件描述符在多个位置生成输出,只要重定向相应的文件描述符就行了

临时重定向【不懂】

永久重定向

  • 重定向stdout
#!/bin/bash 
exec 1>testout   #exec会启动一个新shell并将stdout文件描述符重定向到文件。脚本中发给stdout的所有输出会重定向到testout。  1是stdout的文件描述符

echo "redirecting all output"
echo "to another file."
echo "without have to redirect ---->testout"

执行脚本

$ bash script.sh 
$ cat testout 
redirecting all output
to another file.
without have to redirect ---->testout
  • 重定向stderr
#!/bin/bash 
exec 2>error

echo "redirecting all error" >&2
echo "to another file."  >&2
echo "without have to redirect ---->error"  >&2

重定向输入

#!/bin/bash 
exec 0< error  #告诉shell它应该从文件error中获得输入,而不是stdin
count=1

while read line
do
	echo "Line $count:$line"
	count=$[ $count + 1]
done

创建自己的重定向

在脚本中重定向输入与输出时,并不局限于这3个[0、1、2]默认的文件输入符。还是用使用3~8之间的文件描述符作为输入或者输出重定向[在shell中最多可以有9个打开的文件描述符]

创建输出文件描述符

一旦将另一个文件描述符分配给一个文件,这个重定向就会一直有效,直到重新分配。

#!/bin/bash 
exec 3>output  #exec命令将文件描述符3重定向到另一个文件。
# exec 3>>output # 追加

echo "display on the monitor"
echo "this shold be stored in the file -- output" >&3  #这一行会重定向到output
echo "back on the monitor"

创建输入文件描述符

下面的例子时:testfile --> 0 —> 6 —>0【终端输入】

#!/bin/bash 
# redirecting input file descriptors 
exec 6<&0 
exec 0< testfile 
count=1 
while read line 
do 
	echo "Line #$count: $line" 
	count=$[ $count + 1 ] 
done 
exec 0<&6 
read -p "Are you done now? " answer 
case $answer in 
	Y|y) echo "Goodbye";; 
	N|n) echo "Sorry, this is the end.";; 
esac

你可能感兴趣的:(#,linux与shell脚本编程)