Sponsored Content
Top Forums UNIX for Advanced & Expert Users When is a _function_ not a _function_? Post 302832043 by Don Cragun on Friday 12th of July 2013 02:54:40 PM
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:
 
All times are GMT -4. The time now is 04:13 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy