Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
929 views
in Technique[技术] by (71.8m points)

shell - Bash script error: "function: not found". Why would this appear?

I'm trying to run a bash script on my Ubuntu machine and it is giving me an error:

function not found

To test, I created the following script which works fine on my laptop but not on my Desktop. Any ideas as to why? My laptop is a mac if that's relevant.

#!/bin/bash

function sayIt {   
   echo "hello world"
}

sayIt

This returns "hello world" on my laptop, but on my Desktop it returns:

run.sh: 3: function not found hello world run.sh: 5: Syntax error: "}" unexpected

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Chances are that on your desktop you are not actually running under bash but rather dash or some other POSIX-compliant shell that does not recognize the function keyword. The function keyword is a bashism, a bash extension. POSIX syntax does not use function and mandates the use of parenthesis.

$ more a.sh
#!/bin/sh

function sayIt {   
   echo "hello world"
}

sayIt
$ bash a.sh
hello world
$ dash a.sh
a.sh: 3: function: not found
hello world
a.sh: 5: Syntax error: "}" unexpected

The POSIX-syntax works in both:

$ more b.sh
#!/bin/sh

sayIt () {   
   echo "hello world"
}

sayIt
$ bash b.sh
hello world
$ dash b.sh
hello world

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...