help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to have local variable but must behave like a plain variable


From: Greg Wooledge
Subject: Re: How to have local variable but must behave like a plain variable
Date: Sat, 26 Aug 2023 08:38:58 -0400

On Sat, Aug 26, 2023 at 02:17:55PM +0700, Budi wrote:
> How to have local variable but must behave just a simple / plain
> variable which is retaining its value all the time, no matter how many
> time exit and enter the function

You're talking about a "local static" variable, or at least that's
what it's called in C.

Bash doesn't have those.

If you need persistence, you have two choices: a global variable, or
a file.  The global variable could be given a name that contains the
function's name, to minimize the chances of someone else using it.

For example, in a function named foobar, I might suggest something like
this:

_foobar_counter=0
foobar() {
    local foo bar x y z
    let '_foobar_counter++'
    printf 'foobar has been called %d times\n' "$_foobar_counter"
    ...
}



reply via email to

[Prev in Thread] Current Thread [Next in Thread]