4

i'm coding a simple bash script and i found this error syntax error at line XX `(' unexpected my code:

function myfun(){
   echo XXXX
   echo YYYY
   read choice
}

choice=$(myfun)

where is the error. i used the ShellCheck and no errors were detected.

BDeveloper
  • 1,175
  • 6
  • 24
  • 44
  • `error syntax error at line` please post the full error message, verbatim, without hiding the line number (what for?) (if so, which line?). Please make sure your scripts doesn't have DOS line endings. – KamilCuk Aug 10 '20 at 13:39
  • Here `myfun(){`, there have to be space, like this `myfun() {`. – Ivan Aug 10 '20 at 13:39
  • 5
    "unexpected (" usually indicates you're running bash code with /bin/sh – glenn jackman Aug 10 '20 at 14:01
  • 3
    If you want the user to select a choice from a menu, use the `select` statement: `select choice in XXXX YYYY; do [[ $choice == "" ]] || break; done; echo "$choice"` – glenn jackman Aug 10 '20 at 14:01
  • 3
    Even in `bash`, the `function` keyword serves no real purpose and can (and should) be omitted). – chepner Aug 10 '20 at 14:05
  • 3
    @Ivan No, that space is not necessary. – chepner Aug 10 '20 at 14:06
  • 1
    The `function` keyword was added to support porting `ksh` scripts to `bash`. `ksh` makes a distinction between functions defined with and without the `function` keyword. `bash` simply allows it to be used; it does not affect the definition in any signifiant way. – chepner Aug 10 '20 at 14:07
  • @chepner yep, my bad, thank you – Ivan Aug 10 '20 at 14:12
  • @secretsquirrel I don't see how that makes a difference. In both cases, you have two options; switch to a syntax which is compatible with the shell you are using, or switch to a shell which is compatible with the syntax you are using. – tripleee Aug 10 '20 at 18:24
  • @triplee, well if the OP accepted the answer below its a moot point; the script doesn't need a shebang if its run as sh script.sh..the code in the accepted answer doesn't run on Ubuntu, there are other problems with the function declaration. I did a version and tested it on Ubuntu and it worked with bash, but with significant changes. – secret squirrel Aug 10 '20 at 20:15

1 Answers1

5

Make sure you are running the script with bash. That error is a commonly seen dash shell error.

I suspect the first line of your script is not #!/bin/bash, i.e. you may have left out the shebang line entirely resulting in the default shell being used (which will often be dash especially on Debian derived Linuxes where /bin/sh -> dash).

Try running this:

#!/bin/bash

myfun()
{
   echo XXXX
   echo YYYY
   read choice
}

choice=$(myfun)
mattst
  • 13,340
  • 4
  • 31
  • 43
  • Of course, with the pesky `function` keyword out of the way, this simple script is now also completely compatible with `/bin/sh`. – tripleee Aug 10 '20 at 18:22