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

请问一个 Bash 的 String Operator 的问题

  •  
  •   fvladlpa · 2015-02-11 19:58:45 +08:00 · 2144 次点击
    这是一个创建于 3354 天前的主题,其中的信息可能已经有所发展或是发生改变。
    做习题的时候遇到这个问题,script是

    #filename is "highest"
    filename=$1
    filename=${filename:?"missing."}
    howmany=$2
    sort -nr $filename | head -${howmany:=10}
    echo "$howmany books have been selected"

    filename中的输入文件中myflie的内容是

    #filename is myfile
    5 Depeche Mode
    2 Split Enz
    3 Simple Minds
    1 Vivaldi, Antonio

    输入

    ./highest myfile 3

    返回内容为

    5 Depeche Mode
    3 Simple Minds
    2 Split Enz
    3 books have been selected

    我设想是如果输入的是

    ./highest myfile

    返回内容应该是

    5 Depeche Mode
    3 Simple Minds
    2 Split Enz
    1 Vivaldi, Antonio
    10 books have been selected

    但是实际上返回的是

    5 Depeche Mode
    3 Simple Minds
    2 Split Enz
    1 Vivaldi, Antonio
    books have been selected

    也就是说 sort -nr $filename | head -${howmany:=10} 执行完之后 $howmany 依然是null而不是10。

    求解各位BASH大神,这是怎么回事?
    3 条回复    2015-02-11 20:55:23 +08:00
    timonwong
        1
    timonwong  
       2015-02-11 20:30:42 +08:00   ❤️ 1
    pipe 那里是开了一个新的subshell (fork),因此${howmany}的变更不会影响到 parent
    fvladlpa
        2
    fvladlpa  
    OP
       2015-02-11 20:45:17 +08:00
    @timonwong 你的意思是subshell和parent里面的${how many}实际上是两个变量。那么请问如果要实现我希望的功能script要怎么写,谢谢
    timonwong
        3
    timonwong  
       2015-02-11 20:55:23 +08:00
    @fvladlpa
    ${howmany:=10} 单独写成一行(或者写成 howmany=${howmany:-10})
    然后
    sort -nr $filename | head -${howmany} 就成了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1405 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:52 · PVG 07:52 · LAX 16:52 · JFK 19:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.