我在一份脚本中找到了这行代码。虽然我大致明白它的作用——打开一个双向TCP连接——但是我需要对语法进行解释。以下是该行代码:
exec 5<>"/dev/tcp/${SERVER}/${PORT}"
我的问题:
<
和>
通常用于重定向IO。那在这里它是什么意思?它能在其他情况下使用吗?如何使用?/dev/tcp
不存在,为什么它可以工作?- 为什么是5?它可以是另一个数字吗?允许使用哪些值?
- 为什么需要使用
exec
?(考虑到实际上没有任何东西被执行)
谢谢。
我只能回答执行部分:
如果没有给出命令,exec 可以用于更改 I/O 重定向。在这种情况下,<> 意味着打开读写。5 是通道号(或文件描述符)。如果其他命令从通道 5 发送其输出 / 读取其输入,则这是有意义的。
对于 "/dev/tcp/${SERVER}/${PORT}",我不知道它是特定 Linux 版本的功能还是 bash 的功能(我认为是后者)。
-- 编辑:来自 bash 手册页面:--
Bash handles several filenames specially when they are used
in redirections, as described in the following table:
/dev/fd/fd
If fd is a valid integer, file descriptor fd is
duplicated.
/dev/stdin
File descriptor 0 is duplicated.
/dev/stdout
File descriptor 1 is duplicated.
/dev/stderr
File descriptor 2 is duplicated.
/dev/tcp/host/port
If host is a valid hostname or Internet address,
and port is an integer port number or service
name, bash attempts to open a TCP connection to
the corresponding socket.
/dev/udp/host/port
If host is a valid hostname or Internet address,
and port is an integer port number or service
name, bash attempts to open a UDP connection to
the corresponding socket.