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?

3
  • 2
    python -c "print \"$arg\"" works for me. Commented Apr 20, 2015 at 14:09
  • 2
    or even python -c "print '$arg'" Commented Apr 20, 2015 at 14:10
  • 2
    The syntax highlighting shows the problem :-) Commented Apr 20, 2015 at 18:47

2 Answers 2

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

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

1 Comment

Found a nice resource on concatenating strings here stackoverflow.com/questions/4181703/…
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

6 Comments

Awsome explanation bro +1, but you shud have posted it a little early!
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: 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?
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
@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!
|

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.