When is a _function_ not a _function_?


 
Thread Tools Search this Thread
Top Forums UNIX for Advanced & Expert Users When is a _function_ not a _function_?
# 1  
Old 07-12-2013
When is a _function_ not a _function_?

For a starter I know the braces are NOT in the code...

Consider these code snippets:-
Code:
#!/bin/bash --posix
x=0
somefunction()
if [ $x = 0 ]
then
	echo "I am here."
fi
# somefunction





#!/bin/bash --posix
x=0
somefunction()
if [ $x = 0 ]
then
	echo "I am here."
fi
somefunction





#!/bin/bash --posix
x=0
somefunction()
echo "Why does this crash?"
if [ $x = 0 ]
then
	echo "I am here."
fi
somefunction

Now using OSX 10.7.5 and bash here is the result:-
Code:
Last login: Fri Jul 12 18:41:45 on ttys000
AMIGA:barrywalker~> ./func.sh
AMIGA:barrywalker~> ./func.sh
I am here.
AMIGA:barrywalker~> ./func.sh
./func.sh: line 4: syntax error near unexpected token `echo'
./func.sh: line 4: `echo "Why does this crash?"'
AMIGA:barrywalker~> _

Why do the first two snippets work as predicted, (although without the braces), yet the third crashes out with the error report?
What is going on?

Can someone explain what is going on?

Many thanks...
# 2  
Old 07-12-2013
Quote:
Originally Posted by wisecracker
For a starter I know the braces are NOT in the code...

Consider these code snippets:-
Code:
#!/bin/bash --posix
x=0
somefunction()
if [ $x = 0 ]
then
	echo "I am here."
fi
# somefunction


#!/bin/bash --posix
x=0
somefunction()
if [ $x = 0 ]
then
	echo "I am here."
fi
somefunction


#!/bin/bash --posix
x=0
somefunction()
echo "Why does this crash?"
if [ $x = 0 ]
then
	echo "I am here."
fi
somefunction

Now using OSX 10.7.5 and bash here is the result:-
Code:
Last login: Fri Jul 12 18:41:45 on ttys000
AMIGA:barrywalker~> ./func.sh
AMIGA:barrywalker~> ./func.sh
I am here.
AMIGA:barrywalker~> ./func.sh
./func.sh: line 4: syntax error near unexpected token `echo'
./func.sh: line 4: `echo "Why does this crash?"'
AMIGA:barrywalker~> _

Why do the first two snippets work as predicted, (although without the braces), yet the third crashes out with the error report?
What is going on?

Can someone explain what is going on?

Many thanks...
According to the standards, the body of a function definition is a compound command. The most common compound command used when defining a function is a brace group, such as:
Code:
somefunction() {
    echo "Why does this crash?"
}

but other compound commands include if statements, subshells, for loops, case statements, while loops, and until loops. The echo command by itself is not a compound command.
These 5 Users Gave Thanks to Don Cragun For This Post:
# 3  
Old 07-12-2013
Hi Don Cragun...

Thanks for the prompt reply.

All logged into the old grey matter for future use...
Login or Register to Ask a Question

Previous Thread | Next Thread
Login or Register to Ask a Question