Embedding Python code in Bash shell Script

Nowadays, Python is a popular scripting language, especially in data science and automation. You can integrate Python code very easily in bash scripts. We have used here doc for this purpose.

Let's write the shell script embed_01.sh as follows:

#!/bin/bash 
function now_date_time 
{ 
python - <<START 
import datetime 
value = datetime.datetime.now() 
print (value) 
START 
}  
now_date_time 
Date_Time=$(now_date_time) 
echo "Date and time now = $Date_Time"

Let's test the program as follows:

    $ chmod +x embed_01.sh
    $ ./ embed_01.sh
  

The output is as follows:

    2018-04-27 01:53:58.719905
    Date and time now = 2018-04-27 01:53:58.770123
  

Let's see an example of using bash variables in embedded Python code.

Let's write ...

Get Learning Linux Shell Scripting - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.