0

I have a collection of bash functions that include a verbosity level option. According to the set value, different levels of outputs are generated. The verbosity is local to each function.

But I also have environment variables. One of them also specifies a verbosity level. It is a global verbosity tool specifically implemented to affect new terminal shells. If the environment variable is used and set to level 1, a summary of terminal commands available is printed.

Suppose a function is called with a verbosity positional argument, whilst the environment variable is also set, what would most users expect the behavior to be? To enforce the local verbosity setting, or to use the environment variable level?

1
  • 3
    Please edit your question and show us some actual code. We can't help you understand the behavior of code we cannot see. Anything and everything could happen, depending o exactly how you use the variable and how the functions read it and how they're run etc. Commented Sep 20, 2022 at 12:41

1 Answer 1

0

Functions are not subshells. Any changes you make to variables in the function will propagate unless you append them with local

You can make a function a subshell by wrapping it in parenthesis ()

In the example test.sh:

#!/bin/env bash

function amiasubshell {
    DISPLAY=$1
    echo amiasubshell: $DISPLAY
}

function nobuticanfakeit {
    local DISPLAY=$1
    echo nobuticanfakeit: $DISPLAY
}

echo main: $DISPLAY
amiasubshell :2
echo main: $DISPLAY
(amiasubshell :5)
echo main: $DISPLAY
nobuticanfakeit :28
echo main: $DISPLAY

The first instance of amiasubshell changes the value moving forward in the main body. The second instance does not because it is a subshell. The instance of nobuticanfakeit only changes the value in the context of the function because it is a local variable:

main: :0
amiasubshell: :2
main: :2
amiasubshell: :5
main: :2
nobuticanfakeit: :28
main: :2
3
  • I understand that. The question is about something else. Suppose I have a local verbosity vb and a global verbosity gvb. And one calls a function using the local verbosity, but ho also has the global verbosity gvb enabled to same other level. Would users expect the function to use the global value level in gvb or still continue using the local value vb? Commented Sep 21, 2022 at 13:02
  • Having some random functions that don't respect the global verbosity level is counter intuitive. Commented Sep 22, 2022 at 1:28
  • Which answers an important question as I do not want things counter intuitive to users. Commented Sep 22, 2022 at 1:45

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.