美文网首页
missing之bash脚本编写-4

missing之bash脚本编写-4

作者: 墨道院 | 来源:发表于2021-01-13 18:31 被阅读0次

    用通配符和大括号实现的shell globbing 的便利功能

    当调用脚本的时候,你可能会输入一些类似的,同质的选项。正好Bash有一些技巧可以扩展文件的后缀名,叫做shell globbing,中文我也暂时不知道怎么翻译。

    • 通配符(Wildcards ). 做通配符匹配的时候,我们可以使用?或者*。问号?只匹配一个字符,星号*可以匹配任意个字符。比如有这样几个文件:foo, foo1, foo2, foo10 以及 bar,命令rm foo?将会删除foo1和foo2,而rm foo*将会删除除了bar以外所有的文件。
    • 大括号({}). 当一些类似的命令里里有一些字符串,他们虽然不一样,但是比较类似,就可以用大括号来做一些处理。

    看看下面的例子:

    convert image.{png,jpg}
    # Will expand to
    convert image.png image.jpg
    
    cp /path/to/project/{foo,bar,baz}.sh /newpath
    # Will expand to
    cp /path/to/project/foo.sh /path/to/project/bar.sh /path/to/project/baz.sh /newpath
    
    # Globbing techniques can also be combined
    mv *{.py,.sh} folder
    # Will move all *.py and *.sh files
    mkdir foo bar
    # This creates files foo/a, foo/b, ... foo/h, bar/a, bar/b, ... bar/h
    touch {foo,bar}/{a..h}
    touch foo/x bar/y
    # Show differences between files in foo and bar
    diff <(ls foo) <(ls bar)
    # Outputs
    # < x
    # ---
    # > y
    

    编写Bash脚本是一件非常反直觉的事情,因此有个工具shell check可以像编译器那样检查你的脚本写的是否有问题。

    相关文章

      网友评论

          本文标题:missing之bash脚本编写-4

          本文链接:https://www.haomeiwen.com/subject/hwlpaktx.html