coding-guidelines icon indicating copy to clipboard operation
coding-guidelines copied to clipboard

Bash - Flag constants as read-only

Open MrChocolatine opened this issue 2 years ago • 5 comments

Global constants

In your coding guidelines:

https://github.com/mullvad/coding-guidelines/blob/5c5931de7a7b0efde46a3fc91d3ec62ec10a58a4/bash.md?plain=1#L58-L62

May I suggest to also declare these as readonly for more strictness?

The above example would become:

readonly SCREAMING_SNAKE_CASE="something"

Your usual:

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

would become:

readonly SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

Local/scoped constants

On a very similar note, for variables scoped to their function with local:

https://github.com/mullvad/coding-guidelines/blob/5c5931de7a7b0efde46a3fc91d3ec62ec10a58a4/bash.md?plain=1#L94-L104

For those that should be constants, additionally to having them written in uppercase you could also declare them as read-only with local -r:

function cowsay { 
    local -r COW_PREFIX="The cow says"
    local message="$1" 
    echo "$COW_PREFIX: $message" 
} 

MrChocolatine avatar Jun 28 '22 13:06 MrChocolatine