Bash Variable – Syntax & Examples

Bash Variable

Bash Variable in bash shell scripting is a memory location that is used to contain a number, a character, a string, an array of strings, etc.

Some important points to remember about variables in bash scripting

  • There are no data types for a variable. It can contain a number, a character, a string, an array of strings, etc. and be overridden with any other value.
  • There is no need to declare a variable explicitly. When you assign a value to the reference, variable declaration happens implicitly.

We shall go through the following topics in this tutorial

Syntax

Following is the syntax to initialize a variable

Note : No space should be given before and after  = , failing which produces error “syntax error near unexpected token“.

 

Examples for Bash Variable

Following example demonstrates simple initialization of bash variables of types : number, character, string and array.

When the above bash variable example is run in Terminal,

 

Bash Local Variable

Bash Local Variable is used to override a global bash variable, in local scope, if already present with the same name.

Syntax

Following is the syntax of a bash local variable

Example

Following is an example bash script to demonstrate the usage of local variable

When above bash local variable example is run in Terminal

The first echo statement is in global scope and SHELL  has value of UNIX, but when bashShell  function is called, the local variable SHELL  overrides the global variable and hence the echo $SHELL  echoed Bash.

 

Conclusion :

In this Bash TutorialBash Variable, we have learnt that there are no data types in bash, and the syntax to initialize a variable, and also about local bash local variables with example scripts.