Error Handling and API Calls
Process exit codes can be used to do a quick assessment of successful completion, however it should be kept in mind that checking the error codes alone cannot guarantee output is error free and as you expect it to be.
“?” env variable contains the exit code for the last run process in session, where a 0 denotes a successful process exit while 1 denotes a failure. This variable when coupled with conditional statements can bring in some basic error handling capabilities to your scripts.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#do something if error code denotes a failure | |
if [ $? -gt 0 ]; then | |
echo "something went wrong!" | |
fi | |
#status checking in command pipe | |
cat textfile.txt | ( [[ $? == 0 ]] && grep "cat" ) |
A simple way to validate API calls would be to utilize the -v flag in cURL client to print out a verbose output and then redirect the output to a grep to be asserted for a predefined value.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
curl -X GET -v $ENDPOINT > RESPONSE | |
cat $RESPONSE | grep -i "success" |
Functions
Bash provides limited capability to abstract out code to create functions, find more about its capabilities with regard to functions here[2]. As BASH is not capable of creating user defined data types, you might find yourself in a situation where you need to return a bunch of data items back to the caller. A crude way in which this requirement can be achieved is by dividing the data items with a unique delimiter and then breaking up the values on the caller side using awk.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
findproductnames() | |
{ | |
DELIMITER="*" | |
PROD_ONE="Apache JMeter" | |
PROD_TWO="Apache Tomcat" | |
echo $PROD_ONE$DELIMITER$PROD_TWO | |
return | |
} | |
FUNCTION_CALL_RETURN_VALUES="$(findproductnames)" | |
echo $FUNCTION_CALL_RETURN_VALUES | |
VALUE_ONE="$(echo $FUNCTION_CALL_RETURN_VALUES | awk -F '*' '{print $1}')" | |
VALUE_TWO="$(echo $FUNCTION_CALL_RETURN_VALUES | awk -F '*' '{print $2}')" | |
echo $VALUE_ONE$VALUE_TWO |
When you start resorting to elaborate methods to get simple tasks done, you are probably extending BASH beyond its capabilities and it’s time to move onto a more capable language such as python.
[1] - https://www.gnu.org/software/bash/manual/html_node/
[2] - http://www.linuxjournal.com/content/return-values-bash-functions