Scripting
When plain Bash is not enough

When plain Bash is not enough

I recently read an excellent introductory Bash tutorial on Dev.to by Sahil Bondre.

It is a really great tutorial on shell scripting basics, but I remember when I was beginning my adventure with shell scripting and I became fascinated with Bash. In fact, I was a bit over-fascinated with it. With my neuroimaging scripts becoming more and more complex, I slowly began loosing control over my code! Many times I felt like:

Linux bash why won't you work - crying peter parker | Meme Generator

The Python era

That’s when I discovered, that at some point, with complex logic (more conditionals, loops, and functions), it’s worth switching to Python instead. With Python you can wrap (almost) any bash command. And it is as simple as:

import subprocess as sp

bash_command = "ls ~/"
print("\nBash command:\n%s\n" % bash_command)

process = sp.Popen(bash_command, stdout=sp.PIPE, shell=True)
output, error = process.communicate()

print("\nBash command output:\n%s\n" % output)
print("Bash command error:\n%s\n" % error)

The above example was inspired by this StackOverflow answer.

It turned out that Python syntax is more readable and easier to maintain 🙂

How To Write Better Python Code? - DEV

Python is just a better “pseudocode compiler” than Bash.

Take ~/ message

I just stuck with plain bash for too long — when all I really needed was Python. Nevertheless, for very simple use cases i still use good ol’ Bash!

Leave a Reply