Skip to content

Bash - Flag constants as read-only #17

@MrChocolatine

Description

@MrChocolatine

Global constants

In your coding guidelines:

* Constant variables use `SCREAMING_SNAKE_CASE` names.
This means variables that are assigned once and then never modified, and that only depend on
other constant variables. The exception to "never modified" is where multiple statements are
used to compute the content of the "constant" (see `COMPILE_FLAGS` in example at the end).

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:

coding-guidelines/bash.md

Lines 94 to 104 in 5c5931d

Use `local` for variables inside functions unless they need to be global for some reason
(They most likely should not be). This stops execution of functions from polluting the global
namespace. Do this both for constants and other variables.
```bash
function cowsay {
local COW_PREFIX="The cow says"
local message="$1"
echo "$COW_PREFIX: $message"
}
```

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" 
} 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions