0

I have the following code where if a certain condition is true i try to execute a python code inside a shell script. The issue is i keep getting an IndentationError: unexpected indent and i am not sure why because this indention works fine when i execute the python code outside of the if statement.

if [ ! -z "$INSTANCE_ID" ]
then
      python -c \
      """
      from mydbmodule import db
      update_string = \
      'Update release_status SET release_deployed_at = NOW() \
      where release_deployed_at is null'

      db.execute(db.get_environment(), update_string)
      """
fi
Dinero
  • 1,070
  • 2
  • 19
  • 44
  • 1
    Does this answer your question? [Multi-line string with extra space (preserved indentation)](https://stackoverflow.com/questions/23929235/multi-line-string-with-extra-space-preserved-indentation) – Brian McCutchon Feb 20 '21 at 20:21
  • 2
    Your string is indented. Also, triple-quote strings aren't really a thing in bash; use single-quote strings or heredocs. – Brian McCutchon Feb 20 '21 at 20:22
  • @BrianMcCutchon is the string not suppose to be identend? i am confused – Dinero Feb 20 '21 at 20:23
  • Does this answer your question? [How to indent with "python -c" on the command line](https://stackoverflow.com/questions/61636539/how-to-indent-with-python-c-on-the-command-line) – mkrieger1 Feb 20 '21 at 20:24
  • @mkrieger1 kind of but since i am executing only if statement is true don't i have to ident whatever python code i am executing? – Dinero Feb 20 '21 at 20:25
  • Any indentation you put in the string will be a part of the string. So no, it's not supposed to be indented (at least, not after the line with the open quote). – Brian McCutchon Feb 20 '21 at 20:26
  • 2
    The Python code should not be indented because, from Python's point of view, it is at the top level. Python doesn't know about what happens in your Bash code. – Brian McCutchon Feb 20 '21 at 20:29
  • @BrianMcCutchon ah that makes sense! thank you for the tip. i was under the impression since we are executing a shell script everything inside the if statement has to be indented. – Dinero Feb 20 '21 at 20:30
  • For an explanation of why triple quotes look like they work, see https://stackoverflow.com/questions/55978911/what-does-triple-single-quote-mean-in-bash – Brian McCutchon Feb 20 '21 at 20:40

1 Answers1

0

This works:

if true; then
    python -c \
"
print ('test message')
"
fi

So does this:

if true; then
    python -c "
print ('test message')
"
fi

this raises an indentation error:

if true; then
    python -c \
"
    print ('test message')
"
fi

because the string Python gets is indented while it shouldn't be.

As for """, in the shell it's pretty much the same as just one quote: """foo""" has three quoted strings, "", "foo", and "". The first and third are just empty and don't do anything.

ilkkachu
  • 6,221
  • 16
  • 30
the.real.gruycho
  • 608
  • 3
  • 17