Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a variable as static in shell bash function like C?

Tags:

c

linux

bash

shell

In C, I can define a static variable in a function like this

int func() {
    static int var=0
    .....
}

Is there something equivalent to that in shell bash linux?

Is it possible to define a local variable of the bash shell function as static?

like image 400
MOHAMED Avatar asked Jan 02 '14 13:01

MOHAMED


People also ask

How do you set a variable in bash shell?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.

Can you declare variables in bash?

A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it.

What is static variable C?

What is a Static Variable? In programming, a static variable is the one allocated “statically,” which means its lifetime is throughout the program run. It is declared with the 'static' keyword and persists its value across the function calls.

Can static variables be changed in C?

When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program.


2 Answers

With bash you cannot really get that (I imagine you want some variable shared between several instances of your shell...). However, if you switch to the fish shell (use chsh to change your login shell), you get so called universal variables which kind-of fits the bill. See also this answer to a related question.

BTW, you should read advanced bash scripting guide and consider using bash functions (instead of a script).

If you just want to share a variable between several shell functions inside the same shell process, just don't declare it local to functions!

like image 113
Basile Starynkevitch Avatar answered Sep 25 '22 22:09

Basile Starynkevitch


If you want the static variable to be used within a bash function and to have the life of the bash script you can define and initialize it before the function, making it global, and then use it, without initialization, within the function. The value will have the life of the script.

#!/bin/bash

variable=0

increment()
{
    (( variable++ ))
    echo $variable
}

while true; do
    increment
    sleep 1
done

This will output an incrementing number.

like image 33
ClearCrescendo Avatar answered Sep 24 '22 22:09

ClearCrescendo