BASH 中的空函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30998558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:15:09  来源:igfitidea点击:

Empty function in BASH

bashubuntulinux-mint

提问by user3550394

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

我正在使用 FPM 工具来创建 .deb 包。此工具在从支持的文件中删除包之前/之后创建。

Unfortunatly the bash script generated by FPM contains such function

不幸的是,FPM 生成的 bash 脚本包含这样的功能

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?

BASH 不允许空函数吗?哪个版本的 bash/linux 有这个限制?

回答by orestiss

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

您可以使用:它等效于true并且主要用作什么都不做操作符...

dummy(){
     : 
  }

回答by JobJob

A one liner

一个班轮

dummy(){ :; }

dummy(){ :; }



:is the null command

:是空命令

;is needed in the one line format

;需要单行格式

回答by YangwuWang

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

空的 bash 函数可能是非法的。只包含注释的函数也会被认为是空的。

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

如果你想“什么都不做”,可以在函数中放置一个“:”(空命令)

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

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

回答by Damian Trzeciak

I recommend this one:

我推荐这个:

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

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



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

如果您使用:null 命令,它将通过 xtrace 选项打印:

(
    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 "() { unused() { :; } }"
        set -o xtrace
        "$@"        
    )
    time "$@"
}

print_and_run main aaa "bb bb" ccc "ddd"
# output:
# + main aaa 'bb bb' ccc ddd
# ..