shell 的內件命令exec執行命令時,不啟用新的shell進程【注: source 和 . 不啟用新的shell,在當前shell中執行,設定的局部變量在執行完命令后仍然有效;bash或sh 或shell script執行時,另起一個子shell,其繼承父shell的環境變量,其子shelll的變量執行完后不影響父shell,注意三類的區別】exec是用被執行的命令行替換掉當前的shell進程,且exec命令后的其他命令將不再執行。例如在當前shell中執行 exec ls 表示執行ls這條命令來替換當前的shell 即為執行完后會退出當前shell。為了避免這個結果的影響,一般將exec命令放到一個shell腳本中,用主腳本調用這個腳本,調用處可以用bash xx.sh(xx.sh為存放exec命令的腳本)。這樣會為xx.sh建立一個子shell去執行,當執行exec后該子腳本進程就被替換成相應的exec的命令
其中有一個例外:當exec命令對文件描述符操作的時候,就不會替換shell,而是操作完成后還會繼續執行后面的命令
查看系統操作符
[root@localhost ~]# ll /dev/fd/ total 0 lrwx------. 1 root root 64 Jul 2 18:18 0 -> /dev/pts/1 lrwx------. 1 root root 64 Jul 2 18:18 1 -> /dev/pts/1 lrwx------. 1 root root 64 Jul 2 18:18 2 -> /dev/pts/1 lr-x------. 1 root root 64 Jul 2 18:18 3 -> /proc/54592/fd
exec 3<&0 表示將操作符3也指向標准輸入
exec 8<>tmp_in
[root@localhost ~]# echo "ls -li">&8 [root@localhost ~]# echo "free -m">&8 [root@localhost ~]# cat tmp_in df -h ls -li free -m [root@localhost ~]#
應用
#!/bin/bash rm -rf tmp_in mknod tmp_in p exec 8<>tmp_in telnet 127.0.0.1 23 <&8 & echo xxx >>tmp_in sleep echo -e "35quit">>tmp_in