POSIX Shell: Defining variables

📄 OneThingWell.dev wiki page | 🕑 Last updated: Feb 16, 2023

Defining variables in shell works similarly to general programming languages:

a="My string"

Multiple variables can be defined on the same line:

a="My string" b=42

It's important to mention that, unlike in many programming languages, there can't be a whitespace character between the equals sign:

a = 42

This will fail because whitespace is a delimiter, and the shell will try to execute the a command with = as the first argument, and 42 as the second argument:

a: command not found

There is a potential pitfall, for example, if you do:

x= test

You won't see any errors, but the value of x won't be test, x will be empty; why is that?

Shell will split x= test into two parts, the first one being:


This will set x to an empty value (equivalent to x="").

And the second part is the test command, which will be executed but won't do anything without extra arguments (you can try this by executing just test in your shell).

It may be worth mentioning that this syntax (i.e. x=val cmd) won't redefine our previously defined variable x, but will pass the environment variable named x into the subprocess.

This brings us to the next topics: referencing variables and scoping.

Comments and suggestions

You can use this form to submit a suggestion or a comment.

If you find this site useful in any way, please consider supporting it.