> For the complete documentation index, see [llms.txt](https://morgan-bin-bash.gitbook.io/bash-scripting/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://morgan-bin-bash.gitbook.io/bash-scripting/how-to-assign-variable-in-bash.md).

# How to Assign Variable in Bash

A variable is a named storage location in a program's memory where a value can be stored, retrieved, and manipulated. Like any programming language, Variables are an essential component in the Bash scripts. They allow you to create dynamic scripts that can change based on the data that is passed to them.

In Bash, there are different ways to assign variables which will be covered in detail.

#### Local vs Global variable assignment

Bash has two types of variables - local, and global based on the scope where they are defined in the script.

**Local variable**

A local variable is a variable that is defined within a function or a block of code and can only be accessed within that function or block. Local variables are only accessible within the function or block in which they are defined and the value of the variable is lost once the function or the block ends.

**Global variable**

A global variable, on the other hand, is a variable that is defined outside of any function or block and can be accessed from any part of the program. Global variables are accessible from anywhere in the program, including from within functions and blocks.

See the following script to understand the scope and lifetime of local vs global variables:

| `#!/bin/bash` `num=2function` `demo_local_var() {       local` `num=1       echo` `"This is the local variable: $num"}` `echo` `"Global num before function: $num"demo_local_varecho` `"Global num after function: $num"` |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

In the script:

* *num=2* initializes the global num variable.
* *local num=1* declared inside the *function demo\_local\_va*r block initializes the local num variable whose scope is within the function only
* Outside this function, echoing $num always prints the value of global num variable.

<figure><img src="https://linuxopsys.com/wp-content/uploads/2023/04/varTypes-02042023-01-1024x198.png" alt="Local vs Global variable" height="198" width="1024"><figcaption></figcaption></figure>

#### Single variable assignment

In bash, a single variable can be assigned simply using the syntax

```
var_name=<value>
```

with no space before and after the **\`=\`** sign. You do not need to declare the data type in bash while assigning a variable.

**Integer assignment**

To assign an integer to a variable, you can use the following syntax:

| `#!/bin/bash` `num=1echo` `$num` |
| -------------------------------- |

In the script, *num=1* assigns a global integer variable value 1.

<figure><img src="https://linuxopsys.com/wp-content/uploads/2023/04/intVar-02042023-02-1024x144.png" alt="integer variable assignment" height="144" width="1024"><figcaption></figcaption></figure>

**String assignment**

There are multiple ways to assign strings:

* Single words can be assigned directly without any quotes.
* Multi-word strings can be defined using Single quotes (') and Double quotes (").

However, there is a difference between how Bash interprets single quotes and double quotes.

When you use single quotes to define a string, it preserves the literal value of each character. On the other hand, if you use double quotes, it recognizes the special symbols ($, \`, \\) and expands the strings using the shell expansion rules.

| `#!/bin/bashname=worldgreeting2='Hello $name'greeting3="Hello $name"` `echo` `$nameecho` `$greeting2echo` `$greeting3` |
| ---------------------------------------------------------------------------------------------------------------------- |

In this example,

* *greeting2* treats *$name* as a string and thus it gets expanded to *Hello $name*.
* While *greeting3* expands *$name* to *world*, thus generating the string - *Hello world*.

<figure><img src="https://linuxopsys.com/wp-content/uploads/2023/04/stringVar-02042023-03-1024x212.png" alt="string variable assignment" height="212" width="1024"><figcaption></figcaption></figure>

**Boolean assignment**

To assign a boolean value to a variable, you can use the following syntax:

| `#!/bin/bash` `true_val=truefalse_val=false` `if` `[[ "$true_val"` `== true` `]]; then       echo` `"true_val: true"fi` `if` `[[ "$false_val"` `== true` `]]; then       echo` `"false_val: true"fi` |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

In the script:

* *true\_val=true* and *false\_val=false* initializes the boolean variables.
* We can use these booleans in conditional statements to make decisions.

<figure><img src="https://linuxopsys.com/wp-content/uploads/2023/04/boolVar-02042023-04-1024x139.png" alt="boolean variable assignment" height="139" width="1024"><figcaption></figcaption></figure>

#### Multi-variable assignments

Bash provides a straightforward syntax for assigning multiple variables in a single line as follows:

| `#!/bin/bash` `a=1 b=2 c=3echo` `"a: $a"echo` `"b: $b"echo` `"c: $c"` |
| --------------------------------------------------------------------- |

<figure><img src="https://linuxopsys.com/wp-content/uploads/2023/04/multiVar-02042023-05-1024x211.png" alt="multiple variable assignment" height="211" width="1024"><figcaption></figcaption></figure>

In the above script, *a=1, b=2, c=3* initializes three integer variables using a single statement.

#### Default value assignment

Bash has a built-in syntax for providing default values to the variables:-

```
newVar=${var:-defaultval}
```

If var is not defined, it assigns the defaultval to the newVar.

See the following script to see how default assignments work:

| `#!/bin/bash` `var1=5` `## first exampleuserOutput1="${var1:-var1 is not defined}"echo` `$userOutput1` `## second exampleuserOutput2="${var2:-var2 is not defined}"echo` `$userOutput2` |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

In script:

* In the first example, *echo $userOutput1* prints *5* to the stdout since *var1* is defined.
* In the second example, *echo $userOutput2* prints *var2 is not defined* since var2 is not defined before.

<figure><img src="https://linuxopsys.com/wp-content/uploads/2023/04/defaultVar-02042023-06-1024x215.png" alt="assign default value to the variable" height="215" width="1024"><figcaption></figcaption></figure>

#### Using let command for assignments

The [let](https://linuxopsys.com/topics/bash-let-with-examples) command is used to assign numeric values to the variables and perform arithmetic, bitwise, and logical operations.

Consider the following script:

| `#/bin/bash` `## Numeric assignmentlet` `"num1 = 1"echo` `"num1: $num1"` `## Additionlet` `"num1 = 1"` `"num2 = num1 + 2"echo` `"$num1 + 2 = $num2"` `## Subtractionlet` `"num1 = 3"` `"num2 = num1 - 2"echo` `"$num1 - 2 = $num2"` `## Multiplicationlet` `"num1 = 2"` `"num2 = num1 * 2"echo` `"$num1*2 = $num2"` `## Divisionlet` `"num1 = 4"` `"num2 = num1 / 2"echo` `"$num1 / 2 = $num2"` `## Moduluslet` `"num1 = 4"` `"num2 = num1 % 2"echo` `"$num1 % 2 = $num2"` `## Exponentiationlet` `"num1 = 4"` `"num2 = num1 ** 2"echo` `"$num1 ** 2 = $num2"` `## Unary post incrementlet` `"num1 = 4"` `"num2 = num1++"echo` `"$num1 after unary post increment = $num2"` `## Unary pre incrementlet` `"num1 = 4"` `"num2 = ++num1"echo` `"$num1 after unary pre increment = $num2"` `## Left shiftlet` `"num1 = 4"` `"num2 = num1 << 1"echo` `"$num1 << 1 = $num2"` `## Right shiftlet` `"num1 = 4"` `"num2 = num1 >> 1"echo` `"$num1 >> 1 = $num2"` `## Bitwise Negationlet` `"num1 = 4"` `"num2 = ~num1"echo` `"~$num1 = $num2"` `## Bitwise ANDlet` `"num1 = 6"` `"num2 = num1 & 2"echo` `"$num1 & 2 = $num2"` `## Bitwise ORlet` `"num1 = 4"` `"num2 = num1 \| 1"echo` `"$num1 \| 2 = $num2"` `## Bitwise XORlet` `"num1 = 4"` `"num2 = num1 ^ 2"echo` `"$num1 ^ 2 = $num2"` |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

<figure><img src="https://linuxopsys.com/wp-content/uploads/2023/04/letCmd-02042023-07-1024x547.png" alt="assign numeric values to the variables using let" height="547" width="1024"><figcaption></figcaption></figure>

let command is an important utility which provides a simplistic syntax to perform a variety of arithmetic, logical and bitwise operations.

#### Using Read command

Bash has a built-in read command that can read a line from the standard input (stdin) and split the line into multiple variables.

See the following script to understand how the read command works:

| `#!/bin/bashecho` `"Enter the animal name and its color"read` `animal colorecho` `"animal: $animal, color: $color"` |
| ------------------------------------------------------------------------------------------------------------------- |

<figure><img src="https://linuxopsys.com/wp-content/uploads/2023/04/readCmd-02042023-08-1024x197.png" alt="read into multiple variables" height="197" width="1024"><figcaption></figcaption></figure>

In the script *read animal color* accepts 2 inputs from the user and stores them in the variables *animal* and *color*.

Read command also comes with some useful options:

* Prompt

Prompt flag (-p) helps to provide a useful text to the user and accept inputs. This removes the additional need for echo statements simplifying the code.

* Silent

Silent flag (-s) helps the user to hide the input from display. This is useful when entering sensitive information such as passwords.

* Input to array

Array (-a) flag reads the input to an array instead of individual words.

| `#!/bin/bash` `read` `-p "Enter the username: "` `usernameread` `-s -p "Enter the password: "` `passwordechoread` `-p "Enter your hobbies(space separated): "` `-a hobbies` `echo` `"$username logged in"echo` `"Your hobbies are:-  "` `for` `hobby in` `${hobbies[@]}; do       echo` `$hobbydone` |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

In the script:

* *read -p “Enter the username: “*  prints the text “Enter the username: “ and also accepts an input from the user.
* *read -s -p “Enter the password: “*  accepts an input from the user in silent mode, i.e. it is not displayed on the screen.
* *read -p “Enter your hobbies(space separated): “ -a hobbies* accepts an array input from the user into *hobbies* variable. The variable can then be iterated over using the array iteration syntax.

<figure><img src="https://linuxopsys.com/wp-content/uploads/2023/04/readCmdWithOpts-02042023-09-1024x382.png" alt="" height="382" width="1024"><figcaption></figcaption></figure>

### Conclusion

* Bash supports both local and global variables. Using global variables, in general should be avoided since they increase the complexity of the code and may introduce hard to debug bugs.
* Bash provides built-in support for assigning integer, strings and boolean type variables. Data type is not required while assigning variables.
* Multiple variables can be assigned simply by defining multiple variables in a single line.
* Bash also supports initializing variables with default values. This is a good programming practice and helps to avoid bugs due to uninitialized variables.
* The let command is a useful built-in in bash for working with numerics and performing a variety of operations.
* The read command is another important built-in to read input from the command line and create interactive applications.
