-3

I have an array in bash script. This script gets executed through python send command and while executing the array line of the script,

it returns -

Syntax error: "(" unexpected

due to this line of code -

pci_addr_0=`lspci | grep -i abcde | grep -i "\.0 " | awk -F " " {'print $1'}`

pci_addr_list_0=(`echo $pci_addr_0 | tr " " "\n"`)

I tried slash and double quotes, but the array doesn't get assigned with values as expected.

How to avoid python from invalidating bash array braces?

RV5
  • 1
  • 1
  • Can you show us the entire function or the whole code? I have a feeling you are mixing Python and Bash code together in one script. – Siddharth Dushantha Aug 03 '21 at 07:28
  • @RV5: From the bash side, the assignment looks OK. Could it be that this is not executed by bash? Do a `echo $BASH_VERSION` just before the line which gives the error. Also, show the Python command which initiates the whole stuff. – user1934428 Aug 03 '21 at 08:55
  • always put full error message (starting at word "Traceback") in question (not comment) as text (not screenshot, not link to external portal). There are other useful information. – furas Aug 04 '21 at 12:38
  • 1
    show your Python code. You can't use `bash` code directly in `Python`. You would need to use `os.system("bash code")` or `subprocess.run("bash code", shell=True)`. Do you use `pexcept`? Show it in question. – furas Aug 04 '21 at 12:40
  • @furas, it's `sh` code, not `bash` code, in both cases. `shell=True` and `os.system()` both use `/bin/sh`, which is not bash (or, if it is bash, runs in compatibility mode, turning off some features and syntax) – Charles Duffy Aug 04 '21 at 16:11
  • ...and in this case, the OP's problem was caused by the lack of a `#!/bin/bash` shebang to force the shell used to be bash instead of sh. – Charles Duffy Aug 04 '21 at 16:12

1 Answers1

0

Thanks all!

I was using python expect to call another bash script, no mixing.

Got it resolved by explicitly adding #!/bin/bash to the bash script. Until then, most of the commands worked in that bash script and didn't notice this could be a potential issue.

@user1934428 good idea, i will check this.

RV5
  • 1
  • 1
  • Note that the new code is not good form -- `array=( $(yourcommand) )` is an antipattern; see [BashPitfalls #50](http://mywiki.wooledge.org/BashPitfalls#hosts.3D.28_.24.28aws_....29_.29). Best practices for iterating over input line-by-line are given in [BashFAQ #1](http://mywiki.wooledge.org/BashFAQ/001), though to just read into an array in bash 4.0 or later you can use `readarray -t array < <(yourcommand)` – Charles Duffy Aug 04 '21 at 16:13