skip to Main Content

I need to run a bash script and get the output. The script has a loop with avariable.

It works on terminal screen when I paste bash script only, but it gives error when I use subprocess by using Python. Here is the code:

import subprocess

text1 = """
declare -a StringArray=("a1" "a2" "a3" "a4" "a5" )
for val in ${StringArray[@]}; do
   echo $val
done
"""
text_output = (subprocess.check_output(text1, shell=True).strip()).decode()

This is the error:

/bin/sh: 2: Syntax error: "(" unexpected
Traceback (most recent call last):
.
.
.
' returned non-zero exit status 2.

What is the solution?

Python3.7, OS: Debian-like Linux, Kernel: 4.19.

2

Answers


  1. You can use subprocess.Popen in this case.

    Below is the code that can help you achieve the above. Please let me know if you have any question.

    >>> import subprocess
    >>> cmd = 'declare -a StringArray=("a1" "a2" "a3" "a4" "a5" );for val in ${StringArray[@]}; do echo $val; done'
    >>> x=subprocess.Popen(cmd,shell=True)
    >>> a1
    a2
    a3
    a4
    a5
    
    Login or Signup to reply.
  2. The error message states: /bin/sh .... Python does not use bash as you expect. It uses another shell. (On my system sh is dash.) And it seems that this other shell does not support the StringArray=("a1" "a2" "a3" "a4" "a5" ) syntax.

    You can try to explicitly select bash like this:

    subprocess.check_output(text1, shell=True, executable='/bin/bash')
    

    (At least, /bin/bash works on my system.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search