Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass multiple args from bash into python

I have a short inline python script that I call from a bash script, and I want to have it handle a multi-word variable (which comes from $*). I expected this to just work:

#!/bin/bash

arg="A B C"
python -c "print '"$arg"'"

but it doesn't:

  File "<string>", line 1
    print 'A
           ^
SyntaxError: EOL while scanning string literal

Why?

like image 512
Barry Avatar asked Apr 20 '15 14:04

Barry


2 Answers

The BASH script is wrong.

#!/bin/bash

arg="A B C"
python -c "print '$arg'"

And output

$ sh test.sh 
A B C

Note that to concatenate two string variables you don't need to put them outside the string constants

like image 108
Bhargav Rao Avatar answered Sep 21 '22 04:09

Bhargav Rao


I would like to explain why your code doesn't work.

What you wanted to do is that:

arg="A B C"
python -c "print '""$arg""'"

Output:

A B C

The problem of your code is that python -c "print '"$arg"'" is parsed as python -c "print '"A B C"'" by the shell. See this:

arg="A B C"
python -c "print '"A B C"'"
#__________________^^^^^____

Output:

  File "<string>", line 1
    print 'A

SyntaxError: EOL while scanning string literal

Here you get a syntax error because the spaces prevent concatenation, so the following B and C"'" are interpreted as two different strings that are not part of the string passed as a command to python interpreter (which takes only the string following -c as command).

For better understanding:

arg="ABC"
python -c "print '"$arg"'"

Output:

ABC
like image 30
aldeb Avatar answered Sep 18 '22 04:09

aldeb