在 bash/Shell 脚本中调用函数

Sam*_*dey 2 bash shell

当我在 shell 脚本中调用函数时,就像它不工作一样

testfunction
Run Code Online (Sandbox Code Playgroud)

但是如果我像下面这样调用函数,它就可以工作

$(testfunction);
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?我在 Ubuntu 上运行 bash shell

谢谢你,桑巴夫

大家好, 这是一个示例脚本和函数 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 
Run Code Online (Sandbox Code Playgroud)

eck*_*kes 5

$(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
Run Code Online (Sandbox Code Playgroud)

跟进您的评论,您的问题似乎是与<<. 这里的文档基本上是一个多行字符串:

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
Run Code Online (Sandbox Code Playgroud)

或者,您可以结束此处的文档:

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
Run Code Online (Sandbox Code Playgroud)