Empty function in BASH

16.5k views Asked by At

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?

5

There are 5 answers

0
YangwuWang On

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

2
orestiss On

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

dummy(){
     : 
  }
1
JobJob On

A one liner

dummy(){ :; }


: is the null command

; is needed in the one line format

0
Fedor On
dummy_success(){ true; } #always returns 0
dummy_fail(){ false; }   #always returns 1

minimal functions returning always OK or ERROR status..

also useful to redefine missing functions with empty function (or update it with some default action, for example - debug warning):

#!/bin/sh
#avoid error if calling unimportant_func which is underfined
declare -F unimportant_func >/dev/null || unimportant_func() { true; }
    
#get error if calling important_func which is underfined
declare -F important_func >/dev/null || important_func() { false; }

# print debug assert if function not exists
declare -F some_func >/dev/null || some_func() {
    echo "assert: '${FUNCNAME[0]}() is not defined. called from ${BASH_SOURCE[1]##*/}[${BASH_LINENO[0]}]:${FUNCNAME[1]}($@)" 1>&2; }


my_func(){
    echo $(some_func a1 a2 a3)
    important_func   && echo "important_func ok"   || echo "important_func error"
    unimportant_func && echo "unimportant_func ok" || echo "unimportant_func error"
}

my_func

output:

$> testlib.sh
assert: 'some_func() is not defined. called from testlib.sh[15]:my_func(a1 a2 a3)

important_func error
unimportant_func ok
0
Damian On

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
# ..