3

When building bash scripts, I use a lot of readonly and local -r when making variables. That rapidly fills a script and makes the code less readable (and repetitive). Is there a way (like a set flag at the top of the script) to make all variables readonly and/or local -r by default?

With the added caveat, it has to work on 3.2.57(1)-release, as I’m on macOS.

I’m pretty sure this isn’t possible, but want to make sure.

Please don’t answer “drop bash and use a proper scripting language”. I use other scripting languages as well. bash scripts have their place and I like coding them.

2 Answers 2

1

Is there a way (like a set flag at the top of the script) to make all variables readonly and/or local -r by default?

No, unless you include editing the source to bash.

However, you can declare an alias so that the semantic sugar required to set a variable read-only is reduced.

For example,

#!/bin/bash
#
shopt -s expand_aliases
alias lr='local -r'

demo() {
    lr a=123
    echo "$a"
    ((a++))      # Correctly fails with "a: readonly variable"
}

demo
2
  • The problem with the answer is that it doesn’t answer the question, which was about changing a behaviour.
    – user137369
    Jun 21, 2020 at 17:46
  • 1
    @user137369 thank you. Would you be happier if I started my answer with, "There is no way to invert the declaration of a variable..."?
    – roaima
    Jun 21, 2020 at 18:06
-2

By using the declare function you can make your variables read-only. When used in a function declare makes the variable local.

The syntax for declare is this:

declare arg VARIABLE=value

To make a variable read-only you use the -r argument:

declare -r num=12

More can be found here: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_01.html

Not sure if this is exactly what you are looking for but I think it's about as good as you're going to get with BASH

1
  • 1
    That still only works on one variable at a time.
    – user137369
    Apr 6, 2017 at 17:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .