2

The following code:

#!/bin/bash

function me-test()
{
        echo 'test'
}

me-test

The execution method below is not correct:

#sh 1.sh
1.sh: line 6: `me-test': not a valid identifier

but the execution method below is correct:

#./1.sh
test

In other programming languages,it can not using dash to define function.For example,python.

why shell is so that?

baozailove
  • 159
  • 2
  • 14
  • 1
    Also, the `function` syntax is not standard, and may not work with all posix-compatible shells. – rici Aug 17 '16 at 04:00
  • For anyone looking for a direct answer to the question about bash allowing a hyphen character in function names see: https://unix.stackexchange.com/q/168221/7084. Also regarding bash specifically, the bash manual says that "In default mode (as opposed to POSIX mode), a function name can be any unquoted shell word that does not contain `'$'`". See https://www.gnu.org/software/bash/manual/bash.html#Shell-Functions. – Michael Burr Jul 05 '22 at 21:08

1 Answers1

1

sh 1.sh runs the script as a Bourne Shell script and ./1.sh runs it as a bash script because of your line #!/bin/bash (this is called a shebang which tells the shell which interpreter to use) calls the bash interpreter to run the script. bash allows for hyphens in function names but Bourne Shell does not. The two are very similar but different programming languages.

If you changed #!/bin/bash to #!/bin/sh you'd get an error every time you ran the program.

anishsane
  • 20,270
  • 5
  • 40
  • 73
Mike
  • 3,830
  • 2
  • 16
  • 23