9

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?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Barry
  • 286,269
  • 29
  • 621
  • 977

2 Answers2

16

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

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • 3
    Found a nice resource on concatenating strings here http://stackoverflow.com/questions/4181703/how-can-i-concatenate-string-variables-in-bash – Bhargav Rao Apr 20 '15 at 14:17
10

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
aldeb
  • 6,588
  • 5
  • 25
  • 48
  • 1
    Awsome explanation bro +1, but you shud have posted it a little early! – Bhargav Rao Apr 20 '15 at 14:43
  • Can you clarify why `python -c "print '"A B C"'"` gives a SyntaxError? I'm not sure I follow. What happens to the spaces? – Barry Apr 20 '15 at 15:15
  • @Barry: For sure. 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). Is it more clear? – aldeb Apr 20 '15 at 15:28
  • Argh! Bro ya take away my silver medal! :( Lool anyway the better answer deserved it and yours certainly deserves the accept. Cheers and all the best – Bhargav Rao Apr 20 '15 at 15:50
  • @BhargavRao: Loool really apologize bro! Didn't mean to do that. Just wanted to add some clarifications to the OP's question :p I'm sure and hope you'll get it back sooner! Thanks a lot! – aldeb Apr 20 '15 at 15:54
  • No problem bro! The correct answer should be on top. And it is. That is the way SO works. And you'll get a bronze soon ;) – Bhargav Rao Apr 20 '15 at 15:55