Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between myFun() and function myFun

Tags:

function

bash

As a new(ish) user to bash, what is the difference between myFun() and funtion myFun? I have run into both, not just in people's code but in tutorials as well. Is there any difference between the two? When I tried it out, nothing different seems to happen, so I am fairly sure that these two methods to define a function are just different syntactically and are not run differently at all, but could someone confirm this assumption?

like image 928
Pip Avatar asked Jul 30 '26 09:07

Pip


1 Answers

There is a big difference between these two syntaxes for defining functions:

   name() compound-command
   function name compound-command

The former is POSIX and, therefore, widely portable. The latter is not. Otherwise, they are identical.

Examples

dash is the default shell (/bin/sh) on debian-like systems. Observe that, under dash, this method of defining a function is successful:

$ fn() { date; }
$ fn
Mon Nov 24 14:27:49 PST 2014

But, this method is not:

$ function fn { date; }  
dash: 2: function: not found

There is a similar error under ash (busybox's shell):

$ function fn { date; }
-sh: function: not found
like image 74
John1024 Avatar answered Aug 01 '26 23:08

John1024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!