Over-complicating for fun: Mixing Bash and Python

Ben Haham Hay
2 min readApr 15, 2023

--

I once had to rewrite a Python script in Bash to support customers who can’t or won’t install Python in their environments.

The obvious straightforward solution was to write a Bash version of the same simple script and distribute both versions to customers.

It got me thinking, can I create one script that will run on both Bash and Python?

The rules are:

  1. You must not pass the script any prior information on the environment
  2. The interpreter cannot throw/display errors for invalid commands or statements

Observation #1: Comments

Comments begin with ‘#’ in Python and Bash.

This allows me to use Shebang to achieve a natural script execution from the shell — i.e. ./script.sh.

Observation #2: Strings

Strings are available in both Python and Bash.

Python treats all strings as values that can be assigned to variables. In addition, Python allows for any object to exist on a line without any assignment. Bash on the other hand allows escaping command line and arguments in quotes in addition to variables assignment. This is allowed to cope with space-containing paths.

For example:

“/home/user/my directory/myprog” arg1 “arg 2”

Observation #3: eval

Bash contains an eval construct that allows us to execute shell script code from a string.

This is particularly useful to avoid errors on invalid constructs in Python because the eval arguments are encapsulated in a string.

The script

Combining these 3 observations yields:

#!/bin/bash
"eval" "echo 'hello from shell script!'; exit 1"
def main():
print("hello from python!")
if __name__ == "__main__":
main()

Running in bash:

Line #2 — eval — is run, and since it contains an exit statement does not continue to the Python code which is invalid in Bash.

Running in Python:

Line #2 is composed of a concatenation of strings and serves as a no-op in Python.

The Python interpreter continues to execute the regular Python code after this line.

Note: You do have to run the Python interpreter explicitly to run:

python script.sh

--

--

Ben Haham Hay

Software developer for more than 10 years. Interested in security, programming, new technologies and self improvement