2017-03-18 61 views
0

我想从命令提示符调用一个函数,但我找不到调用它的正确方法。如何调用函数

这是我的脚本:

echo "Hello World!" 

test { 

    echo "Sample message" 
} 

我尝试以下方法:

sh-4.2$ main.sh test                                      
Hello World!                                        
./main.sh: line 5: usuage: command not found                                
A helpful message!                                      
./main.sh: line 8: syntax error near unexpected token `}'                             
./main.sh: line 8: `}'                   


sh-4.2$ . main.sh test()                                     
sh: syntax error near unexpected token `(' 

你能帮我解决这个问题吗?

+0

@Inian,刚刚添加。 – user3181365

+0

使用我的答案在下面! – Inian

回答

2

夫妇在这里的问题,为test函数的语法是错误的,你需要周围有括号,

test() { 
    echo "Sample message" 
} 

export -f test 

export -f语法允许您将功能输出到shell;从你需要源脚本,在当前shell作为命令行运行它们,

$ . ./main.sh 
Hello World! 

现在你可以直接在命令行从脚本已经远销之后调用函数test

$ test 
Sample message 

另外一个很好的做法不是有功能名称test,因为它是同名的shell内置。推荐使用一些自定义名称。