1

I need to pass a list of strings from python to shell script.

Goal: Inside the Shell script,

1)The shell script should accept that list of strings which is passed as a parameter.

2)I need to loop that list and print the strings inside the loop.

What I had tried:

main.py

import subprocess
ssh_key_path = #KEY_PATH
ip_address = #BASTION_IP
Details = #Somedata
list_1 = ["apple","banana","carrot"]
script = subprocess.call([sh,fruits.sh,ssh_key_path,ip_address,Details,list_1])

fruits.sh

ssh -i $1 ubuntu@$2 -o StrictHostKeyChecking=no << EOF
   printf $3 >/home/Details.txt
   fruits = $4
   for i in $4; do
     echo "$i"
   done
   echo "Success" 
EOF

Output from fruits.sh:(Expected Output)

apple
banana
carrot
Success

Error: expected str, bytes, or os.PathLike object, not list.

So,How to pass the list to shell script and execute inside it.?

1 Answer 1

1

Just join with spaces. For example:

test.py

import subprocess

fruits = ["apple","banana","carrot"]

subprocess.call(["sh", "test.sh", "hello", " ".join(fruits)])

test.sh

echo "greeting: $1"

for i in $2
do
    echo "fruit: $i"
done

Output:

greeting: hello
fruit: apple
fruit: banana
fruit: carrot

The basic point here is that you are passing a single string argument, and your shell script is then splitting it as required.

But if you cannot use space as a separator, then you will have to use multiple arguments. For example:

test.py

import subprocess

fruits = ["green apple", "yellow banana", "orange carrot"]

subprocess.call(["sh", "./test.sh", "hello"] + fruits)

test.sh

echo "greeting: $1"

shift

for i in "$@"
do
    echo "fruit: $i"
done

output:

greeting: hello
fruit: green apple
fruit: yellow banana
fruit: orange carrot

Here the shift in the shell script will drop the first argument from the argument list, so that the "$@" will loop over the remaining arguments. (Repeat shift as many times as necessary.)

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

Comments

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.