What is the use case of noop [:] in bash?

后端 未结 12 928
滥情空心
滥情空心 2020-12-12 13:07

I searched for noop in bash (:), but was not able to find any good information. What is the exact purpose or use case of this operator?

I tried following and it\'s w

12条回答
  •  萌比男神i
    2020-12-12 13:19

    Two of mine.

    Embed POD comments

    A quite funky application of : is for embedding POD comments in bash scripts, so that man pages can be quickly generated. Of course, one would eventually rewrite the whole script in Perl ;-)

    Run-time function binding

    This is a sort of code pattern for binding functions at run-time. F.i., have a debugging function to do something only if a certain flag is set:

    #!/bin/bash
    # noop-demo.sh 
    shopt -s expand_aliases
    
    dbg=${DBG:-''}
    
    function _log_dbg {
        echo >&2 "[DBG] $@"
    }
    
    log_dbg_hook=':'
    
    [ "$dbg" ] && log_dbg_hook='_log_dbg'
    
    alias log_dbg=$log_dbg_hook
    
    
    echo "Testing noop alias..."
    log_dbg 'foo' 'bar'
    

    You get:

    $ ./noop-demo.sh 
    Testing noop alias...
    $ DBG=1 ./noop-demo.sh 
    Testing noop alias...
    [DBG] foo bar
    

提交回复
热议问题