-3

I have the following script

list=\(\)
val=123
list+=\(\"$val\"\)

When I copy-paste it to the terminal it works fine, but when I try to run it from inside a .sh file, I get this error:

file.sh: 9: file.sh: list+=("123"): not found

I found this answer here, but it doesn't seem applicable since I'm not using a space.

btw, I use \ in front of ( because otherwise I get Syntax error: "(" unexpected, this also happend only when running from a script file.

What causes the error?

I'm working on GNU bash, version 4.3.30(1)-release (x86_64-pc-linux-gnu)

Dotan
  • 6,602
  • 10
  • 34
  • 47
  • 5
    The error occurs because you're not using bash. – melpomene Nov 19 '17 at 16:00
  • 3
    The `\(` also stops the `(` from being syntactically meaningful (ie. from telling the parser that it's an array being managed). Using a slash tells the shell **not** to treat something as syntax. Of course, that doesn't help when you're running your script with `/bin/sh`, which (1) is not bash, and (2) doesn't have arrays at all. – Charles Duffy Nov 19 '17 at 16:11
  • ...incidentally, this is one of the (more minor) reasons why using `.sh` extensions for bash scripts is a bad idea: It falsely implies that they can be run with `sh`, or use a `#!/bin/sh` shebang. Scripts with shebangs and the `+x` bit are executables, and executables shouldn't have extensions; you don't run `ls.elf`. – Charles Duffy Nov 19 '17 at 16:17
  • @CharlesDuffy, thanks! Write it as an answer and I'll accept it, if you want – Dotan Nov 20 '17 at 08:32

1 Answers1

-1

You are assigning the literal string () to list, not implicitly declaring it as an empty array.

list=()
val=123
list+=("$val")
chepner
  • 497,756
  • 71
  • 530
  • 681