Generic Bash Script

Example of a generic Bash script, equipped with error handling and input validation, to efficiently decode and process Base64-encoded JSON strings using the `jq` tool.

#!/usr/bin/env bash

# This script expects a Base64-encoded JSON string as input.
# It decodes the string, extracts and exports some values from the JSON,
# and then decodes another Base64 string to extract and print a specific value.
# Example Usage to test: history -c && echo "BASE64STRING==" | /path/to/

# Ensure the script exits in case of a non-zero status from any command
# and ensure that pipeline commands return the exit status of the last command to fail.
set -o pipefail -e

# Read the input into the 'params' variable
IFS= read -r params

# Validate input
if [[ -z "$params" ]]; then
    echo "Error: No input provided."
    exit 1

# Check if input is a valid Base64 string
if ! echo "$params" | base64 -d &> /dev/null; then
    echo "Error: Invalid Base64 input."
    exit 1

# Decode the Base64-encoded JSON string
json=$(echo "$params" | base64 -d)

# Validate JSON
if ! echo "$json" | jq empty &> /dev/null; then
    echo "Error: Invalid JSON."
    exit 1

# Check for the existence of the 'jq' tool, which is required for parsing JSON
if ! command -v jq &> /dev/null; then
    echo "Error: jq is not installed. Please install jq and try again."
    exit 1

# Check for required keys
for key in providerRecordUid resourceRecordUid userRecordUid newPassword oldPassword user records; do
    if ! echo "$json" | jq -e ."$key" &> /dev/null; then
        echo "Error: Key '$key' not found in JSON."
        exit 1

# Extract and export key-value pairs from the JSON string
eval $( echo "$json" | jq -r 'keys[] as $k | "export \($k)=\(.[$k])"' )

# Print the exported values to the terminal
echo "providerRecordUid=$providerRecordUid"
echo "resourceRecordUid=$resourceRecordUid"
echo "userRecordUid=$userRecordUid"
echo "newPassword=$newPassword"
echo "oldPassword=$oldPassword"
echo "user=$user"

# Decode the 'records' variable, which is expected to be another Base64-encoded JSON string
recordJson=$(echo "$records" | base64 -d)

# Validate inner record JSON
if ! echo "$recordJson" | jq empty &> /dev/null; then
    echo "Error: Invalid JSON in records."
    exit 1

# Extract and print the title associated with the 'providerRecordUid'

title=$(echo "$recordJson" | jq -r ".array[] | select(.uid==\"$providerRecordUid\").title")

echo "Provider Title=$title"

Example command to simulate how the script will be executed by the Gateway:

history -c && echo "ewogICAgInByb3ZpZGVyUmVjb3JkVWlkIjogIjEyMzQ1IiwKICAgICJyZXNvdXJjZVJlY29yZFVpZCI6ICI2Nzg5MCIsCiAgICAidXNlclJlY29yZFVpZCI6ICIxMTIyMzMiLAogICAgIm5ld1Bhc3N3b3JkIjogIm5ld1Bhc3MxMjMiLAogICAgIm9sZFBhc3N3b3JkIjogIm9sZFBhc3M0NTYiLAogICAgInVzZXIiOiAidXNlcm5hbWUiLAogICAgInJlY29yZHMiOiAiZXlKaGNuSmhlU0k2SUZ0N0luVnBaQ0k2SUNJeE1qTTBOU0lzSW5ScGRHeGxJam9nSWxCeWIzWnBaR1Z5SURFaWZWMTkiCn0K" | /path/to/

Last updated