Skip to content

Instantly share code, notes, and snippets.

@pozil
Last active August 23, 2024 16:24
Show Gist options
  • Save pozil/ce21a6dcfc939def4972f56ec9d35646 to your computer and use it in GitHub Desktop.
Save pozil/ce21a6dcfc939def4972f56ec9d35646 to your computer and use it in GitHub Desktop.
Shell scripts that runs anonymous Apex with Salesforce CLI and filters out command output to only display time stamp and debug messages
#!/bin/bash
# Shell scripts that runs anonymous Apex with Salesforce CLI and filters out command output to only display time stamp and debug messages
# Know limitation: the script doesn't support multiline log messages (it will only display the first line)
# Get Apex file path from parameter or ask for it
filePath=""
if [ "$#" -eq 1 ]; then
filePath="$1"
else
echo "Apex file path:"
read filePath
fi
# Run anonymous Apex with the Salesforce CLI
OUTPUT=$(sfdx force:apex:execute -f "$filePath")
EXIT_CODE="$?"
# Check Salesforce CLI exit code
if [ "$EXIT_CODE" -eq 0 ]; then
# Check for Apex runtime error
APEX_ERRORS=$(echo "$OUTPUT" | grep 'Error: ')
if [ "$APEX_ERRORS" != '' ]; then
# Log errors
echo "Apex runtime error:"
echo "$APEX_ERRORS"
EXIT_CODE=-1;
else
# Keep debug log lines only
OUTPUT=$(echo "$OUTPUT" | grep 'USER_DEBUG')
# Simplify debug log: keep time stamp, line number and message only
OUTPUT=$(echo "$OUTPUT" | sed -E 's,([0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]+) \([0-9]+\)\|USER_DEBUG\|\[([0-9]+)\]\|DEBUG\|(.*),\1\tLine \2\t\3,')
echo "$OUTPUT"
fi
else
# Salesforce CLI error
echo "Salesforce CLI failed to execute anonymous Apex:"
echo "$OUTPUT"
fi
echo ""
exit $EXIT_CODE
// Sample anonymous Apex file for trying out run-apex.sh
System.debug('Hello');
System.debug('World!');
@pozil
Copy link
Author

pozil commented Sep 6, 2021

Known limitation: the script does not support multi-line debug log messages. It will only show the first line of the log message.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment