ACA
ACA

Reputation: 47

Run python command inside a bash script and get the result

I would like to run a python command that return true or false inside a bash script:

#!/usr/bin/env bash

Some stuff...
boolean = $(python -c "bool(...operations...)")

The code above is just to sketch the idea. I need boolean to be false or true (bash boolean values) depending on the result of ...operations.... The code above is not working: boolean results to be an empty variable.

Upvotes: 1

Views: 1214

Answers (3)

gboffi
gboffi

Reputation: 25093

Bash has no preconception on boolean values, but if you need your bool to be either false or true, then you can use this snippet

bool=$(python -c 'print("true" if ...operations... else "false")')

E.G.,

$ for a in 4 5 ; do
>    bool=$(python -c 'print("true" if '$a' == 4 else "false")')
>    echo $bool
> done
true
false
$

Upvotes: 1

Alok
Alok

Reputation: 10618

xonsh shell should be useful for such mixing of bash and python

Upvotes: 1

jeremysprofile
jeremysprofile

Reputation: 11474

bool=$(python -c 'print(bool("abc"))') works as expected.

Note that this will return True or False not true or false (i.e., capitalized).

Upvotes: 2

Related Questions