ohmygoddess
ohmygoddess

Reputation: 657

function doesn't work with sh (but works for bash)

When I wrote a shell script with functions defined, I found I got error when using sh to execute, and get correct answer using bash. Here is a demo:

Content of test.sh

#!/bin/sh 
function hello {
   echo "hello $1"
}
hello world

The output of "bash test.sh" is: hello world

The output of "sh test.sh" will give me error.

Why sh cannot get the correct answer when the script contains defined function? I didn't find an answer online. Thank you!


Update: I found another issue after I get rid of "function" keyword. It turned out that in Ubuntu, sh is linked to dash. The grammar for dash is a little different from bash.

  1. When defining a function, avoid using the keyword "function", this format is introduced by ksh.

  2. When comparing two strings, avoid using "==". Just use "=" to compare two strings.

  3. There are more changes. Please refer to the following link:

    https://wiki.ubuntu.com/DashAsBinSh

Upvotes: 2

Views: 2426

Answers (1)

Oct
Oct

Reputation: 1525

Bash and sh do not share exactly the same language.

#!/bin/sh
hello() {
 echo "hello $1"
}

hello "world"

note the absence of the function keyword and the () in the function definition.

About the function keyword: POSIX specifies that a function definition has this form:

fname() compound-command[io-redirect ...]

(note that there's no function keyword). Moreover, in the Reserved Words section you'll find:

The following words may be recognized as reserved words on some implementations (when none of the characters are quoted), causing unspecified results:

[[ ]] function select

So if you want to have a portable function definition, don't use the function keyword.

Use internet to find out more, but be aware of that difference to understand how to write working script for sh.

Upvotes: 7

Related Questions