4

I'm looking to write some tests that will create and execute a bash script. Bash itself has a nice way to do this:

 % cat > run.sh << EOF
 > echo "I ran this"
 > EOF
 % . run.sh
 I ran this

In Python I can do this:

 with open ('run.sh', 'w') as rsh:
    rsh.write('echo "I ran this"\n')
 -- etc ---

This is fine for a short script in Python, but I'm wondering if there is some technique I don't know about that let's me do something like what I can do in bash.

2
  • 4
    Triple quoted string literal? Commented Mar 27, 2018 at 15:15
  • D'oh! I forgot about that. Commented Mar 27, 2018 at 15:21

2 Answers 2

15

You can do this

#! /usr/bin/env python

with open ('run.sh', 'w') as rsh:
    rsh.write('''\
#! /bin/bash
echo "I ran this"
echo "more lines"
''')
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks. I had forgotten about this.
Mostly a style issue, but I wouldn't bother with the backslash. The bash script won't care about an empty line at the start of the script.
@chepner the first line might be the shebang and then it matters
I'd still put the shebang on the first line to avoid the backslash, as it isn't (semantically) relevant to the rest of the content. (Actually, I'd probably not put a shebang at all, if I had any control over the test runner, because it would be running the commands with an explicit shell rather than assuming the test scripts are executable.)
That was my edit too. @chepner. Not sure why it was rejected.
|
0

You Can Use writelines here:

with open ('run.sh', 'w') as rsh:
    rsh.writelines('echo "I ran this"\n')

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.