0

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 2

1

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.)

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

It did not work with /bin/sh: 1: Syntax error: "(" unexpected error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.