exec有两种用法:
1,exec + cmd
2,exec 文件重定向
1:shell的exec内建命令并不启用新的shell,而是用要执行的命令替换当前的shell进程,并将老进程的环境清理掉,而且exec命令后的其他命令不再执行;
example1.1:
1 #!/bin/bash 2 3 echo "hello mysql" 4 exec echo " hello oracle" 5 echo "hello db2"
运行结果如下:
1 hello mysql 2 hello oracle
第5行的hello db2始终不会被执行输出。
example1.2:与find搭配
1 find ./ -mtime 1 -exec rm {} \;
显示结果如下截图:
其中mtime -1是显示一天内modified的文件
其中mtime 1是显示一天之前modified的文件
mtime=last modification time of the target file
ctime=last status change time(via 'chmod' or otherwise)
atime=last access time
2,可以使用exec改变输入输出的重定向
example2.1
1 #!/bin/bash 2 # 使用 'exec' 重定向 标准输入 . 3 4 5 exec 6<&0 # 链接文件描述符 #6 到标准输入. 6 # . 7 8 exec < data-file # 标准输入被文件 "data-file" 替换 9 10 read a1 # 读取文件 "data-file" 首行. 11 read a2 # 读取文件 "data-file" 第二行 12 13 echo 14 echo "Following lines read from file." 15 echo "-------------------------------" 16 echo $a1 17 echo $a2 18 19 echo; echo; echo 20 21 exec 0<&6 6<&- 22 # 现在在之前保存的位置将从文件描述符 #6 将 标准输出 恢复. 23 #+ 且关闭文件描述符 #6 ( 6<&- ) 让其他程序正常使用. 24 # 25 # <&6 6<&- also works. 26 27 echo -n "Enter data " 28 read b1 # 现在按预期的,从正常的标准输入 "read". 29 echo "Input read from stdin." 30 echo "----------------------" 31 echo "b1 = $b1" 32 33 echo 34 35 exit 0