在Bash中,如何找到编号最小的未使用的文件描述符? [英] In Bash, how to find the lowest-numbered unused file descriptor?

查看:125
本文介绍了在Bash中,如何找到编号最小的未使用的文件描述符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个Bash脚本中,是否可以在最小编号的文件描述符尚未使用上打开文件?

我已经查找过如何做到这一点,但似乎Bash总是要求你指定的数量,例如像这样:

  exec 3< / path / to / a / file#打开文件读取文件描述符3. 

我希望能够做到像
$ b

  my_file_descriptor = $(open_r / path / to / a / file)

会打开'file'以读取尚未使用的编号最小的文件描述符,并指定该编号给变量'my_file_descriptor'。

解决方案

我知道这个线程是旧的,但相信最好的答案是缺少的,对于像我这样的人来说,这是一个有用的解决方案。

Bash和Zsh构建了一些不用编写脚本的未使用的文件描述符。 (我发现没有这样的短划线,所以上面的答案可能仍然有用)。

注意:这找到最低的未使用的文件描述符> 10,而不是

  $ man bash / ^ REDIRECTION(第2段)
$ man zshmisc / ^打开文件描述符

使用bsh和zsh的示例



打开一个未使用的文件描述符,并将数字分配给$ FD:

  $ exec {FD}> test.txt 
$ echo line 1>& $ FD
$ echo line 2>& $ FD
$ cat test.txt
line 1
第2行
$ echo $ FD
10#这个数字会有所不同

关闭完成时的文件描述符:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' >

以下显示文件描述符现已关闭:

  $ echo line 3>& $ FD 
bash:$ FD:错误的文件描述符
zsh:10:错误的文件描述符
pre>

In a Bash-script, is it possible to open a file on "the lowest-numbered file descriptor not yet in use"?

I have looked around for how to do this, but it seems that Bash always requires you to specify the number, e.g. like this:

exec 3< /path/to/a/file    # Open file for reading on file descriptor 3.

In contrast, I would like to be able to do something like

my_file_descriptor=$(open_r /path/to/a/file)

which would open 'file' for reading on the lowest-numbered file descriptor not yet in use and assign that number to the variable 'my_file_descriptor'.

解决方案

I know this thread is old, but believe that the best answer is missing, and would be useful to others like me who come here searching for a solution.

Bash and Zsh have built in ways to find unused file descriptors, without having to write scripts. (I found no such thing for dash, so the above answers may still be useful.)

Note: this finds the lowest unused file descriptor > 10, not the lowest overall.

$ man bash /^REDIRECTION (paragraph 2)
$ man zshmisc /^OPENING FILE DESCRIPTORS

Example works with bsh and zsh.

Open an unused file descriptor, and assign the number to $FD:

$ exec {FD}>test.txt
$ echo line 1 >&$FD
$ echo line 2 >&$FD
$ cat test.txt
line 1
line 2
$ echo $FD
10  # this number will vary

Close the file descriptor when done:

$ exec {FD}>&-

The following shows that the file descriptor is now closed:

$ echo line 3 >&$FD
bash: $FD: Bad file descriptor
zsh: 10: bad file descriptor

这篇关于在Bash中,如何找到编号最小的未使用的文件描述符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆