Empty function in BASH

12,853

Solution 1

You could use : that is equivalent to true and is mostly used as do nothing operator...

dummy(){
     : 
  }

Solution 2

A one liner

dummy(){ :; }


: is the null command

; is needed in the one line format

Solution 3

An empty bash function may be illegal. function contains only comments will be considered to be empty too.

a ":" (null command) can be placed in function if you want to "DO NOTHING"

see: http://tldp.org/LDP/abs/html/functions.html

Solution 4

I recommend this one:

dummy(){ unused(){ :;} }


If you use : null command, it will be printed by xtrace option:

(
    set -o xtrace
    dummy(){ :; }
    dummy "null command"
)

echo ------

(
    set -o xtrace
    dummy(){ unused(){ :;} }
    dummy "unused function"
)

output:

+ dummy 'null command'
+ :
------
+ dummy 'unused function'

For debug I use wrapper like this:

main() {(
    pwd # doing something in subshell
)}

print_and_run() {
    clear
    (
        eval "$1() { unused() { :; } }"
        set -o xtrace
        "$@"        
    )
    time "$@"
}

print_and_run main aaa "bb bb" ccc "ddd"
# output:
# + main aaa 'bb bb' ccc ddd
# ..
Share:
12,853

Related videos on Youtube

user3550394
Author by

user3550394

Updated on May 01, 2020

Comments

  • user3550394
    user3550394 almost 4 years

    I'm using FPM tool to create .deb package. This tool create before/after remove package from supported files.

    Unfortunatly the bash script generated by FPM contains such function

    dummy() {
    }
    

    And this script exit with an error:

    Syntax error: "}" unexpected

    Does BASH doesn't allow empty functions? Which version of bash/linux have this limitation?

  • arco444
    arco444 almost 9 years
    Consider adding an example to show OP how to do this in a function. You're correct but this could be a much better answer with the tiniest bit more explanation
  • VasiliNovikov
    VasiliNovikov about 6 years
    also you can probably write true for readability. (I guess not everyone knows or would easily understand what : is.)
  • Marco Roy
    Marco Roy about 5 years
    The spaces a required too! dummy(){:;} will not work.