Bash – How to initialize variables for a script

bashshell-scriptvariable

I have a file that I have some functions to be used by a script.
So in my script I do the following:

source my_functions.sh   

VALUE_A=$(get_proper_value "X")  
[[ -z "$VALUE_A" ]] && echo "Missing value" && exit 1  

THE_URL=$(get_url_of_service "SERVICE_NAME")  
[[ -z "$THE_URL" ]] && echo "Missing URL" && exit 1    

CUSTOMER_ID=$(generate_customer_id "Z")  
[[ -z "$CUSTOMER_ID" ]] && echo "Missing customer id" && exit 1      

etc  

I have 4-5 more such declarations at the top of my script before actually doing any processing.
This seems to clutter the script.

Is there a better approach for this? I was thinking of declaring the variables inside my_functions.sh but I was wondering if that could make it worse as it won’t be clear where these variables are coming from

Best Answer

No, what you are doing is a coding pattern called "guard clauses" which is a good thing to do. Handling these trivial error cases later in the code may make it more complicated than necessary.

Related Question