在脚本中重定向输入

exec命令允许你将STDIN重定向到linux系统上的文件中。

exec 0< testfile

这个命令告诉shell它应该从文件testfile中获得输入,而不是STDIN。

创建自己的重定向

创建输出文件描述符

exec 3>test13out

echo "This should display on the monitor"
echo "and this should be stored in the file" >&3
echo "Then this should be back on the monitor"

这个脚本用exec命令来将文件描述符3重定向到另一个文件位置。

可以使用exec命令来将输出追加到现有文件中,而不是创建一个新文件。

exec 3>>test13out

重定向文件描述符

exec 3>&1
exec 1>test14out
echo "This should store in the output file"
echo "along with this line."

exec 1>&3
echo "Now things should be back to normal"

上例中是怎么从已重定向的文件描述符中恢复。(可以重定向STDOUT的原来位置到另一个文件描述符。然后将该文件描述符重定向回STDOUT)

分析:第一个exec将文件描述符3重定向到文件描述符1的当前位置,也就是STDOUT。

   第二个exec命令将STDOUT重定向到文件。

   第三个exec会将STDOUT重定向到文件描述符3的当前位置。

这种方法是在脚本中临时将输出重定向然后再将输出恢复到通常设备的通用办法。

关闭文件描述符

关闭文件描述符,将它重定向到特殊符号&-。

exec 3>&-
exec 3> test17file
echo "This is a test line of  data" >&3
exec 3>&-
echo "This won't work">&3

一旦关闭了文件描述符,则不能再向脚本中写入任何数据。否则shell会报错的。

exec 3> test17file
echo "This is a test line of  data" >&3
exec 3>&-

cat test17file
exec 3> test17file
echo "This'll be bad" >&3

在关闭文件描述符时还要注意:后期在脚本中打开同一个输出文件,shell会用一个新文件来替换已有文件,如果再输出任何数据,会覆盖已有的文件。如上。

阻止命令输出

如将STDERR重定向到一个null文件的特殊文件。null文件里什么都没有。shell输出到null文件的任何数据都不会保存。

linux系统上null文件的标准位置是/dev/null。重定向到该位置的任何数据都会被丢掉。

ls -al > /dev/null
cat /dev/null

可以在输入重定向将/dev/null作为输入文件。由于/dev/null文件不含有任何内容,程序员通常用它来快速移除现有文件中的数据而不用现删除文件再创建:

cat /dev/null > testfile
cat testfile

testfile依然存在系统上,但现在是空文件,这是清除日志文件的一种通用方式。

原文地址:https://www.cnblogs.com/Caden-liu8888/p/6294865.html