在写shell脚本时,如果多个命令的输入或输出都是同一个文件,而这个文件的路径和名字都很长,则需要书写很多次同样的路径会很浪费时间,我们可以使用exec命令来关联一个自定义的文件描述符到一个特定的文件。
execl 打开文件描述符的语法格式为
#打开文件outputfile并把它关联到文件描述符fd #以覆盖方式打开 exec 3> outputfile #以追加方式打开 exec 4>> outputfile1 #复制一个已经存在的文件描述符 exec 5>& 4 #使用完毕后关闭文件描述符 exec 4>&-
特别注意 fd>, fd>>,以及>&fd的中间都不能有空格。
#!/bin/bash #exec.sh echo "Open file descriptor 3(overwrite mode), which is associated with file log" exec 3> log echo "Open file descriptor 4(append mode), which is associated with file log_1" exec 4>> log_1 echo "Open file descriptor 5, which is associated with file descriptor 5" exec 5>& 3 echo "sending some data..." echo "exec test log" 1 >& 3 echo "exec test log_1" 1 >& 4 echo "exec test log_2" 1 >& 5 echo "Closing fd 3..." exec 3>&- echo "Closing fd 4..." exec 4>&- echo "Closing fd 5..." exec 5>&- ~
原文:https://www.cnblogs.com/tid-think/p/10961973.html