Reputation: 657
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.
When defining a function, avoid using the keyword "function", this format is introduced by ksh.
When comparing two strings, avoid using "==". Just use "=" to compare two strings.
There are more changes. Please refer to the following link:
Upvotes: 2
Views: 2426
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