在 bash/Shell 脚本中调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25214897/
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
Calling function in bash/Shell Script
提问by Sambhav Pandey
When I am calling function in shell script like it's not working
当我在 shell 脚本中调用函数时,就像它不工作一样
testfunction
but if I call function like below it's working
但是如果我像下面这样调用函数,它就可以工作
$(testfunction);
Any thoughts? I am running bash shell on Ubuntu
有什么想法吗?我在 Ubuntu 上运行 bash shell
Thank you, Sambhav
谢谢你,桑巴夫
Hi All, Here is a sample script and function decl. and call. As mentioned in the question the funcation call - function is not working but $(function is working)
大家好, 这是一个示例脚本和函数 decl。并打电话。正如问题中提到的函数调用 - 函数不起作用但 $(function is working)
#!/bin/bash
TITLE=My Title";
########FUNCTIONS
### Function Declaration
test() { echo "echoing test"; }
cat << EOF <html> <head> <TITLE>"$TITLE"</TITLE>
</head>
</body>
### Calling the function here - Not working test
#### The Below function call is working $(test)
</body>
</html>
EOF
回答by eckes
$(cmd)
expands to a string with the result of the cmd executed. It is not often used with functions, but it can be. See this illustration which invokes the function in both styles:
$(cmd)
扩展为一个字符串,执行 cmd 的结果。它不常与函数一起使用,但可以使用。请参阅此插图,它以两种样式调用该函数:
$ cat sample.sh
#!/bin/sh
bla() {
echo something
}
# print something
bla
# record something
BLA=$(bla)
echo recorded: $BLA
###
$ ./sample.sh
something
recorded: something
Following up on your comment, your problem seems to be the "here document" used with <<
. A here document is basically a multi-line string:
跟进您的评论,您的问题似乎是与<<
. 这里的文档基本上是一个多行字符串:
echo "this is a string, bla is not recognized as a function"
echo "this is a string, $(bla) executes the function and replaces the output"
cat << EOF
Multi Line
$(bla)
Document
EOF
Alternatively you can end the here document:
或者,您可以结束此处的文档:
cat << EOF1
<html><header><titl
<title>test</title></header>
<body>
EOF1
# this section is script code, not here-document
bla
#
cat << EOF2
</body></html>
EOF2