Bash Variable

Bash Variable in bash shell scripting is a named reference that stores a value for later use in a script or terminal session. A bash variable can hold text, numbers, command output, paths, arrays, and other string-based values used by commands.

Variables make bash scripts easier to read and maintain. Instead of repeating the same value many times, you can assign it once and reuse it with variable expansion such as $name or ${name}.

Important bash variable rules before writing scripts

  • Bash variables are not declared with fixed data types. A variable value is treated mainly as text, even when it looks like a number.
  • A variable is created automatically when a value is assigned to a valid variable name.
  • Do not put spaces before or after = during assignment. Use name=value, not name = value.
  • Variable names usually contain letters, numbers, and underscores, and should not start with a number.
  • Use quotes around variable expansions when the value may contain spaces, tabs, or special characters.

We shall go through the following topics in this tutorial.

Bash variable assignment syntax

Following is the syntax to initialize a variable.

</>
Copy
variableReference=value

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

The left side is the variable name, and the right side is the value. To read the value later, prefix the variable name with $.

</>
Copy
name="Alice"
echo "$name"

Use braces when the variable name is followed immediately by more characters. This makes the boundary of the variable name clear.

</>
Copy
file="report"
echo "${file}.txt"
echo "${file}_backup.txt"

Bash variable examples for number, character, string, and array values

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

Bash Script File

</>
Copy
#!/bin/bash

# number variable
num=10
echo $num

# character variable
ch='c'
echo $ch

# string variable
str="Hello Bob!"
echo $str

# array variable
arr=( "bash" "shell" "script" )
echo "${arr[0]}"
echo "${arr[1]}"
echo "${arr[2]}"

When the above bash variable example is run in Terminal, we will get the following output.

Output

$ ./bash-variable-example 
10
c
Hello Bob!
bash
shell
script

In the array example, indexes start from 0. Therefore, ${arr[0]} prints the first array element, ${arr[1]} prints the second element, and ${arr[2]} prints the third element.

Bash variable names and assignment mistakes to avoid

A bash variable name should be easy to understand and valid for shell parsing. Names such as file_name, count, and backup_dir are safe choices.

</>
Copy
backup_dir="/home/user/backups"
count=5
file_name="notes.txt"

The following assignments are common mistakes. The first one has spaces around =, and the second one starts the variable name with a number.

</>
Copy
name = "Alice"
1name="Alice"

Use meaningful names in real scripts. For example, source_dir is clearer than x when the variable stores a directory path.

Bash variable expansion with quotes

In bash scripting, quoting variable expansions is important when a value contains spaces or special characters. Prefer "$variable" for ordinary string values.

</>
Copy
message="Hello Bash User"
echo "$message"

If you use echo $message without quotes, the script may still appear to work for simple text. However, quoted expansion is safer in commands that process file names, paths, or user input.

</>
Copy
file_name="my notes.txt"
cat "$file_name"

Single quotes and double quotes behave differently. Single quotes preserve the text exactly, while double quotes allow variable expansion.

</>
Copy
name="Bob"
echo 'Hello $name'
echo "Hello $name"
Hello $name
Hello Bob

Bash variable from command output

You can store the output of a command in a bash variable using command substitution. The modern and readable form is $(command).

</>
Copy
today=$(date +%F)
echo "Today is $today"

This is useful when a script needs to build file names, log entries, backup folders, or conditional messages based on command results.

</>
Copy
backup_file="backup-$(date +%F).tar.gz"
echo "$backup_file"

Bash readonly variable for values that should not change

Use readonly when a variable value should not be changed later in the same shell process. This is useful for constants such as script paths, fixed labels, and configuration values.

</>
Copy
readonly APP_NAME="Report Generator"
echo "$APP_NAME"

After a variable is marked readonly, assigning a new value to it causes an error.

</>
Copy
readonly site="TutorialKart"
site="Example"
bash: site: readonly variable

Bash Local Variable

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

In bash, local is used inside a function. The variable exists mainly inside that function call and does not permanently replace the variable with the same name outside the function.

Bash local variable syntax inside a function

Following is the syntax of a bash local variable.

</>
Copy
local variableReference=value

The local keyword should be used inside a function body. It is commonly used to avoid accidental changes to global variables.

Bash local variable example with global and function scope

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

Bash Script File

</>
Copy
#!/bin/bash

# bash variable
SHELL="Unix"

function bashShell {
	# bash local variable
	local SHELL="Bash"
	echo $SHELL
}

echo $SHELL
bashShell
echo $SHELL

When above bash local variable example is run in Terminal, we will get the following output.

Output

arjun@arjun-VPCEH26EN:~/workspace/bash$ ./bash-local-variable-example 
Unix
Bash
Unix

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.

After the function call finishes, the outer SHELL variable still has the value Unix. This is why the third line of output is Unix.

Bash environment variable export

A normal shell variable is available in the current shell. To make a variable available to child processes started from that shell, use export.

</>
Copy
APP_ENV="development"
export APP_ENV
bash -c 'echo "$APP_ENV"'

You can also assign and export in one line.

</>
Copy
export APP_ENV="development"

Use exported variables for settings that another script or command must read. Do not export every variable by default; local script-only values can remain ordinary shell variables.

Bash unset command to remove a variable

Use unset to remove a bash variable from the current shell.

</>
Copy
city="Hyderabad"
echo "$city"

unset city
echo "$city"

After unset city, the variable no longer has a value in the current shell session.

Bash variable examples used in real scripts

The following short script uses variables for a source file, destination directory, and generated backup name.

</>
Copy
#!/bin/bash

source_file="notes.txt"
backup_dir="backups"
backup_file="${backup_dir}/notes-$(date +%F).txt"

mkdir -p "$backup_dir"
cp "$source_file" "$backup_file"

echo "Backup created: $backup_file"

This example shows three common bash variable practices: quote file paths, use braces when combining variable names with other text, and use command substitution when a value must be generated dynamically.

Common bash variable errors and fixes

Error or symptomLikely reasonFix
syntax error near unexpected tokenSpaces around = during assignmentWrite name=value
Variable prints as emptyVariable name is misspelled or unsetCheck the exact name and use echo "$name"
File command fails for names with spacesVariable expansion is not quotedUse "$file_name"
Text after variable name is treated as part of the nameBraces are missingUse ${name}_suffix
Function changes a variable unexpectedlyGlobal variable is modified inside a functionUse local for function-only values

Bash variable FAQ

Do bash variables have data types?

Bash variables do not have fixed data types like many programming languages. Values are mostly stored as strings. Arithmetic operations can treat suitable values as numbers when used in arithmetic contexts.

Why should there be no spaces around = in a bash variable assignment?

In bash, name=value is parsed as an assignment. If you write name = value, bash treats name as a command and = and value as arguments, which causes an error or unexpected behavior.

When should I use ${variable} instead of $variable in bash?

Use ${variable} when the variable is next to other characters, such as ${file}_backup. Braces make the variable name clear and prevent bash from reading the suffix as part of the variable name.

What is the difference between a local variable and an exported variable in bash?

A local variable is limited to a function scope when declared with local. An exported variable is placed in the environment so that child processes started from the shell can read it.

How do I store command output in a bash variable?

Use command substitution with $(command). For example, today=$(date +%F) stores the formatted date output in the variable named today.

Bash variable tutorial QA checklist

  • Confirm every assignment example uses name=value without spaces around =.
  • Check that file path examples quote variable expansions such as "$file_name".
  • Use ${variable} when a variable is joined with suffixes or extensions.
  • Keep local examples inside bash functions only.
  • Use output code blocks only for terminal results, not for executable bash commands.

Bash variable tutorial summary

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.

We also covered variable expansion, quotes, arrays, command substitution, readonly variables, exported environment variables, and common mistakes that occur while writing bash variable assignments.