Search⌘ K
AI Features

Declaration Mechanism: User-Defined Variables

Understand how to declare and reference user-defined variables in Bash scripts. Learn the rules for variable names, how to read variable values, and avoid common errors by using double quotes to prevent unwanted expansions and word splitting.

Declare a variable

Here is an example. Let’s suppose that we want to declare a variable called filename. It stores the README.txt file name. The variable declaration looks like this:

filename="README.txt"

Run the commands discussed in this lesson in the terminal below.

Terminal 1
Terminal
Loading...

We cannot place spaces before and after the equal sign. This works in other programming languages, but not in Bash. For example, the following declaration causes an error:

filename = "README.txt"

Bash misinterprets this line. It assumes that we call the command with the filename name. Then, we pass the two parameters, = and “README.txt”.

When we declare a variable, we can apply Latin letters, ...