3

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.

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

5
  • 1
    From what I know, separating them makes it POSIX compatible Commented Jan 6, 2022 at 18:36
  • Since you're using Bash don't worry about it. Commented Jan 6, 2022 at 18:42
  • 3
    @Fravadona POSIX allows assignments in export commands. Some older shell may not have, which may have led to a belief that export must still be done separately from assignment. Commented Jan 6, 2022 at 18:51
  • A lot of people also use export even when it isn't needed; I wouldn't take a random sample of bash scripts in the wild as indicative of anything resembling good practice. Commented Jan 6, 2022 at 18:53
  • @chepner Thanks for correcting a misconception of mine. I came up with this conclusion by looking at the default ~/.profile and ~/.bash_profile in some Linux distros Commented Jan 6, 2022 at 19:09

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.