Ubuntu bash functions..syntax error: "(" or "}" unexpected

Trying to run some bash functions , but keep encountering syntax error: "(" unexpected. I've try'ed removing the brackets,parenthesis etc etc...nothing seems to work.

$ bash --version
GNU bash, version 4.3.46(1) release

#!/bin/bash
function hello () {
echo "Hello world"
}

Solution 1:

If you are running the script with sh hello.sh, the interpreting shell will not be the one mentioned in the shebang line, but /bin/sh will be used. In case of Debian and Ubuntu by default this will be dash.

So to run your script correctly with a bash, use either of the following.

/bin/bash hello.sh

or

chmod +x hello.sh
./hello.sh

Alternatively you also could set bash as the /bin/sh.

dpkg-reconfigure dash 

Solution 2:

First:

The syntax error is because of (). Remove () from the file like this:

#!/bin/bash
function hello {
echo "Hello world"
}

or you can just run the following command to edit the file for you:

sed -i 's/() //g' hello.sh

You should now be able to run the file with the desired result.


Alternatively:

You could add lines 2, 3, and 4 to your ~/.bashrc file.

function hello () {
echo "Hello world"
}

Remember, do not use sudo to edit your ~/.bashrc file!

After you add the lines to the file, run the following command to restart bash or "source" your .bashrc file:

. ~/.bashrc

You should now be able to run the comand hello and "Hello world" should print in the terminal.


Also:

You could edit the file to say this instead:

#!/bin/bash
echo "Hello world"

and name the file hello and save the file to /usr/local/bin.

After doing all of that, make the file executable by running the following command:

sudo chmod +x /usr/local/bin/hello

You should now be able to run the comand hello and "Hello world" should print in the terminal.


Finally:

A third option would be to add the following line to your ~/.bashrc file:

alias hello='echo "Hello world"'

Then, source your .bashrc file using the following command:

. ~/.bashrc 

Solution 3:

GNU Bash is the shell used by default in terminals on Ubuntu. However when scripts are executed on system boot then dash is used, as it is dash that is /bin/sh.

Won't work-->

$ sh hello.sh

Will work -->

$./hello.sh

Problem solved

Solution 4:

According to your Script:

#!/bin/bash
function hello () {
    echo "Hello world"
}

#call this function as follow:
hello   # Syntax Correct
hello() # Syntax Error