V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
zhanglintc
V2EX  ›  问与答

Shell 中`&-`是什么意思?

  •  
  •   zhanglintc · 2022-11-24 21:03:59 +08:00 · 1245 次点击
    这是一个创建于 490 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如:

    exec 0<&3 3<&-
    exec 5>&-
    

    这里面的&-具体是什么意思?

    第 1 条附言  ·  2022-11-25 10:24:00 +08:00

    类似&1&2这样的是代表文件描述符我是知道的。 ><用于重定向我也知道。

    我只是在意&-是否有什么特殊含义。

    比如echo -的时候,-代表STDIN,所以我好奇&-中的-是否也代表STDIN或者其他什么意思。

    但是man bash grep &-结果如下:

    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.  If >&- or <&- is preceded by {varname}, the value of varname defines the file descriptor to close.
    

    所以可以看出来&-其实没有什么特别的含义,就是随便规定了一个特殊写法,用来关闭file descriptor。 而且exec 3<&-exec 3>&-其实是一样的,都是关闭fd3。


    另外提一嘴,exec command,command会替代当前进程。

    如果是exec 2>/dev/null这种,exec后面跟数字的,当前进程并不会被替换,此时exec只是重定向当前进程的fd。

    9 条回复    2022-11-25 08:52:37 +08:00
    Nitroethane
        1
    Nitroethane  
       2022-11-24 21:10:31 +08:00 via iPhone
    bash 操作文件描述符,具体含义搜一下,经常不用忘掉了
    zhanglintc
        2
    zhanglintc  
    OP
       2022-11-24 21:14:16 +08:00
    @Nitroethane #1 就是没搜到。。。 搜`&-`最终都变成了`&`
    Nitroethane
        3
    Nitroethane  
       2022-11-24 21:16:44 +08:00 via iPhone
    @zhanglintc 看 bash 的手册,搜 file descriptor
    yfugibr
        4
    yfugibr  
       2022-11-24 21:22:12 +08:00 via Android
    搜的时候用引号括起来
    https://www.google.com/search?q=%22%24-%22
    zhanglintc
        6
    zhanglintc  
    OP
       2022-11-24 21:26:57 +08:00
    @Nitroethane #3 嗯,看了下,好像并没有特殊含义。单纯就是规定了一个特殊写法用来 close 一个文件描述符。
    kkwa56188
        7
    kkwa56188  
       2022-11-24 21:29:26 +08:00   ❤️ 1
    &- 是把前面那个 descriptor 关掉.
    ref: https://tldp.org/LDP/abs/html/io-redirection.html
    zhanglintc
        8
    zhanglintc  
    OP
       2022-11-24 22:03:27 +08:00
    @kkwa56188 #7 嗯。这书不错啊。
    julyclyde
        9
    julyclyde  
       2022-11-25 08:52:37 +08:00
    man bash
    搜 REDIRECTION
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3347 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:45 · PVG 18:45 · LAX 03:45 · JFK 06:45
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.