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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.