写在前面:案例、常用、归类、解释说明。(By Jim)
2>将STDEER输入到一个文件
1>将STDOUT输入到一个文件&>将STDEER和STDOUT输入到同一个文件在脚本中重定向输入#!/bin/bash# redirecting file inputexec 0
(从文件testfile中读取数据)
创建自己的重定向#!/bin/bash# using an alternative file descriptorexec 3>testoutecho "This should display on the monitor"echo "This should be stored in the file">&3echo "Then this should be back on the monitor"
(第二行将被写入文件当中)
重定向文件描述符#!/bin/bash# storing STDOUT,then coming back to itexec 3>&1exec 1>testoutecho "This should display on the monitor"echo "This should be stored in the file"echo "Then this should be back on the monitor"exec 1>&3echo "Now things should be back to normal"
(中间的三行将被写入文件testout中,描述符3重定向到文件描述符1的当前位置,也就是STDOUT)
创建输入文件描述符#!/bin/bash# redirecting input file descriptorsexec 6<&0exec 0
(貌似执行完了,又回到请求页面了,如果没有exec 6<&0,就会直接执行完毕了)
关闭文件描述符如果创建新的输入输出文件描述符,shell将在脚本退出时自动关闭它们。但有时需要在脚本结束前手动关闭文件描述符。&-exec 3>&-#!/bin/bash# testing closing file descriptorsexec 3>testfileecho "This is a test line of data">&3exec 3>&-echo "This won't work">&3
(最后一句将不会写入文件,并且报错,因为文件描述符3已经关闭)
列出开放文件描述符lsof命令列出整个Linux系统上所有的开放文件描述符。-p可以指定进程ID(PID)-d可以指定要显示的文件描述符编号禁止命令输出有时候不希望显示任何脚本输出,解决的办法,是将STDERR重定向到称为空文件null file的特殊文件。使用临时文件mktemp命令可以轻松在/tmp文件夹中创建一个唯一的临时文件。它仅向文件所有者分配读取和写入权限,并使您成为文件的所有者。mktemp testing.XXXXXX就会创建一个临时文件#!/bin/bash# creating and using a temp filetempfile=`mktemp test.XXXXXX`exec 3>$tempfileecho "This script writes to temp file $tempfile"echo "This is the first line">&3echo "This is the second line">&3echo "This is the last line">&3exec 3>&-echo "Done creating temp file.The contents are:"cat $tempfilerm -f $tempfile 2>/dev/null
结果:
This script writes to temp file test.tspEXqDone creating temp file.The contents are:This is the first lineThis is the second lineThis is the last line在/temp中创建临时文件-t选项强迫mktemp在系统的临时文件夹中创建文件。但使用该特性时,mktemp命令返回用于创建临时文件的完整路径名[root@localhost shellscript]# mktemp -t test.XXXXXX/tmp/test.v44fqo#!/bin/bash# creating a temp file in /tmptempfile=`mktemp -t test.XXXXXX`exec 3>$tempfileecho "This script writes to temp file $tempfile"echo "This is the first line">&3echo "This is the second line">&3echo "This is the last line">&3exec 3>&-echo "Done creating temp file.The contents are:"cat $tempfilerm -f $tempfile 2>/dev/null
#!/bin/bash# using a temporary directorytempdir=`mktemp -d dir.XXXXXX`cd $tempdirtempfile1=`mktemp temp.XXXXXX`tempfile2=`mktemp temp.XXXXXX`exec 7>$tempfile1exec 8>$tempfile2echo "Sending data to directory $tempdir"echo "This is a test line of data for file1">&7echo "This is a test line of data for file2">&8
记录消息有时很有必要将输出同时发送到监视器和日志文件。tee命令即可。tee命令就像管道的T型接头。它将STDIN的数据同时发送到两个目的地。一个是STDOUT,另一个是tee命令行指定的文件名:如果希望向文件添加数据,则必须使用-a选项:
#!/bin/bash# using the tee command for loggingtempfile=testfileecho "This is the first line"|tee $tempfileecho "This is the second line"|tee -a $tempfileecho "This is the last line"|tee -a $tempfile
(既能显示在屏幕上,又能保存到日志中)