bash: 在循环中创建许多描述符
bash: Creating many descriptors in a loop
我正在尝试为 bash 中名为 1、2、3 等的文件创建多个描述符。
例如,exec 9>abc/1
工作得很好,但是当我尝试在 for 循环中创建描述符时,如下所示:exec $[$i+8]>abc/$i
,它不起作用。我尝试了很多不同的方法,但似乎 exec
就是不接受变量。有什么办法可以做我想做的事吗?
编辑:如果没有,也许有一种方法可以在没有描述符的情况下使用 flock
?
是的,exec
不接受文件描述符编号的变量。正如评论中指出的那样,您可以使用
eval "exec $((i + 8))>"'"abc/$i"'
其中,如果 $i
是 1
,则等同于
exec 9>"abc/$i"
即使文件名更改为与 abc/1
.
不同的名称,那些复杂的引号确保 eval-ed 然后 exec-ed 命令是安全的
但是 there is一个警告:
Redirections using file descriptors greater than 9 should be used with care, as they may conflict with file descriptors the shell uses internally.
因此,如果您的任务不需要连续的文件描述符编号,您可以使用自动分配的描述符:
Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}
. In this case, for each redirection operator except >&-
and <&-
, the shell will allocate a file descriptor greater than 10 and assign it to varname
.
所以,
exec {fd}>"abc/$i"
echo "$fd"
将打开文件描述符 10(或更大)以写入 abc/1
并打印该文件描述符编号(例如 10
)。
我正在尝试为 bash 中名为 1、2、3 等的文件创建多个描述符。
例如,exec 9>abc/1
工作得很好,但是当我尝试在 for 循环中创建描述符时,如下所示:exec $[$i+8]>abc/$i
,它不起作用。我尝试了很多不同的方法,但似乎 exec
就是不接受变量。有什么办法可以做我想做的事吗?
编辑:如果没有,也许有一种方法可以在没有描述符的情况下使用 flock
?
是的,exec
不接受文件描述符编号的变量。正如评论中指出的那样,您可以使用
eval "exec $((i + 8))>"'"abc/$i"'
其中,如果 $i
是 1
,则等同于
exec 9>"abc/$i"
即使文件名更改为与 abc/1
.
但是 there is一个警告:
Redirections using file descriptors greater than 9 should be used with care, as they may conflict with file descriptors the shell uses internally.
因此,如果您的任务不需要连续的文件描述符编号,您可以使用自动分配的描述符:
Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form
{varname}
. In this case, for each redirection operator except>&-
and<&-
, the shell will allocate a file descriptor greater than 10 and assign it tovarname
.
所以,
exec {fd}>"abc/$i"
echo "$fd"
将打开文件描述符 10(或更大)以写入 abc/1
并打印该文件描述符编号(例如 10
)。