2

When I am calling function in shell script like it's not working

testfunction

but if I call function like below it's working

$(testfunction);

Any thoughts? I am running bash shell on Ubuntu

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)

#!/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 
6
  • 2
    Please show how and where you define the function. Commented Aug 9, 2014 at 3:19
  • 1
    "it doesn't work" is the worst possible description. What does happen? What do you expect to happen? How are the answers different? Commented Aug 9, 2014 at 3:27
  • 1
    More importantly actually is that you show your error messages. Commented Aug 9, 2014 at 3:39
  • 1
    You cannot add a statement inside a "here-document". Everything between <<EOF and EOF is a string which gets expanded. So you can only use variables or other expressions (like $()). Commented Aug 9, 2014 at 6:22
  • 1
    @Sambhav You can edit your post. Commented Aug 9, 2014 at 6:34

1 Answer 1

5

$(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:

$ 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
Sign up to request clarification or add additional context in comments.

3 Comments

please add it to your question, then you can format it readable.
Typo: ${bla] should be $(bla) - mine too
Great, Thanks eckes.... About the suggestion for editing the question instead of comment, I will keep in mind from the next time. Best Regards, Sambhav

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.