Here is a fun python and bash tip. This concept is useful for cases where you want to parse a json string in a bash script, or extract a substring, etc.
Here is an example to process json:
#!/bin/bash
j='[{"food":"apple","drink":"tea"},{"food":"burger","drink":"soda"}]'
# parse json from bash using python
python3 -c "
import sys, json
# get the argument passed to python
input = sys.argv[1]
# convert the input to dict
jsn = json.loads(input)
# loop through the json dictionary
for k in jsn:
print(k)
for i in k:
print(i, k[i])
" $j
Here are additional examples of bash and inline python:
#!/bin/bash
# example 1
python3 -c "
import os, time
from datetime import datetime
now = datetime.now()
current_time = now.strftime('%H:%M:%S')
print('Current Time =', current_time)
print('Hello world')
"
Here’s another example that uses python’s argparse library:
# example 2
python3 -c "
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('cloud', help='cloud provider: gcp, aws, azure, vic_vm, etc',
type=str)
args = parser.parse_args()
print(args.cloud)
" gcp