Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Separate declaration from export of variables in bash scripts

I have a bash script like

#!/bin/bash
DATABASE_NAME=my_database
export DATABASE_NAME
run_some_other_command

They first declare the variable and set it to a value, then in a separate line, they export it. Personally, I like to just do it in one line like:

export DATABASE_NAME=my_database

Is there some style rule against this? I’ve seen the declaration and export be separated by others, but never knew why.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If it helps, this script runs on Linux Mint, but could run on other Linux’s or even a Mac.

>Solution :

Because export is a command; when assignment comes from a command or sub-shell output, its own return code will override/mask the return code of the assigning command:

# the return-code of the getDBName function call
# is masked by the export command/statement
export DATABASE_NAME=$(getDBName)
# Separate export
export DATABASE_NAME

# Allow capture and use of the getDBName return code
if ! DATABASE_NAME=$(getDBName)
then printf 'Failed getDBName with RC=%d\n' "$?" >&2
fi
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading