Bash script error: “function: not found”. Why would this appear?

前端 未结 4 1131
轮回少年
轮回少年 2020-12-08 00:09

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

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 00:41

    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
    

提交回复
热议问题