Rules for Naming Bash Variables
Every variable needs a name, and Bash is strict about which names it accepts. Knowing the rules explains why some assignments fail with confusing messages, and a few common naming habits make scripts much easier to read.
What a Valid Name Looks Like
A variable name, which the Bash manual calls an identifier, follows three rules:
- It may contain only ASCII letters (
atoz,AtoZ), digits (0to9), and underscores (_). - It must not start with a digit.
- It is case-sensitive.
These names are all valid:
_x=1
a1=2
MY_VAR=3
my_var=4
Name=5
echo "$_x $a1 $MY_VAR $my_var $Name"
1 2 3 4 5
A name may start with an underscore and may be as long as you like, since Bash sets no practical limit on length.
Names Are Case-Sensitive
Uppercase and lowercase letters count as different characters, so two names that differ only in case are two separate variables:
city="Chennai"
CITY="Delhi"
echo "$city $CITY"
Chennai Delhi
Mixing the case of one name by accident is a common source of bugs, because the misspelled name silently expands to an empty value.
What Happens with an Invalid Name
Bash decides that a line is an assignment only if the text before the equals sign is a valid name. When it is not, Bash treats the whole thing as the name of a command to run, and the error message says "command not found" instead of pointing at the real problem:
1abc=5
my-var=5
my var=5
my.var=5
1abc=5: command not found
my-var=5: command not found
my: command not found
my.var=5: command not found
Each failure has a clear cause:
1abcstarts with a digit.my-varcontains a hyphen, which Bash reads as part of a command name, not as a variable character.my var=5contains a space, so the first word ismy, which is not a command.my.varcontains a period.
Built-in commands that take assignments, such as export and declare, check the name directly and give a more helpful message:
export 1abc=5
export my-var=5
declare 2x=3
export: `1abc=5': not a valid identifier
export: `my-var=5': not a valid identifier
declare: `2x=3': not a valid identifier
Seeing "not a valid identifier" means exactly what it says: the name breaks one of the three rules.
Where the Name Ends in an Expansion
When you use $name, Bash reads letters, digits, and underscores for as long as it can, and the first character that does not fit ends the name. This rule has two consequences.
Text glued to a name is read as part of it when it is a letter, digit, or underscore:
user=ana
echo "$user_name|"
echo "${user}_name|"
|
ana_name|
The first line looked for a variable called user_name, which does not exist, so it printed nothing. Using braces, as in ${user}_name, ends the name after user and keeps the suffix as plain text.
Hyphens inside braces do something unexpected, because ${name-word} is the syntax for "use word if name is unset". A hyphenated name therefore does not produce an error. It gives a surprising value:
my-var=5
echo ${my-var}
var
Here the first line failed (it was not a valid assignment), so the variable my was never set. The expansion then read my as the name and var as the fallback text, and it printed var. A name that begins with a digit is not accepted inside braces at all:
echo "${1x}"
${1x}: bad substitution
Naming Conventions
Beyond what Bash requires, the community follows a few habits that make scripts easier to read. These conventions are not enforced by the shell.
- Use UPPERCASE for environment variables and constants, such as
PATH,HOME,MAX_RETRIES, andBACKUP_DIR. - Use lowercase, with underscores between words, for ordinary variables in a script, such as
file_countorinput_name. - Choose descriptive names.
backup_direxplains itself, whilebddoes not.
The convention for uppercase has a practical reason. Many programs read environment variables written in uppercase, and a lowercase name in your script will not clash with them.
Special Names That Bash Already Uses
Bash defines many variables itself. Overwriting one by accident can change how the shell or your script behaves. Some examples:
| Name | What it holds |
|---|---|
PATH | Directories searched for commands |
HOME | The user's home directory |
IFS | The characters used for word splitting |
PS1 | The text of the interactive prompt |
RANDOM | A new random number on each read |
SECONDS | The seconds since the shell started |
LINENO | The current line number in the script |
UID, EUID | The numeric user ids |
Some are read-only, and Bash refuses to change them. In a script, the error also abandons the rest of that command line, as the tests with Bash 5.2 showed:
UID=5
UID: readonly variable
Others can be changed, with consequences. Setting PATH to a folder with no programs means the shell can no longer find commands such as ls. The next example does it inside a subshell, in parentheses, so that the original PATH stays intact:
( PATH=/nonexistent; ls; echo "status=$?" )
ls: command not found
status=127
Status 127 is the exit code for "command not found". Because the change happened in the subshell, the surrounding script still works normally.
Some special variables have special behavior when assigned. For instance, assigning to RANDOM sets the seed of the random number generator, so the same seed gives the same first number:
RANDOM=42; a=$RANDOM
RANDOM=42; b=$RANDOM
[ "$a" = "$b" ] && echo "same seed, same value"
same seed, same value
To avoid clashes, do not pick names that are all uppercase and common, such as PATH, USER, SHELL, or PWD, for your own values. Lowercase names are safest for script-local data.
Words Reserved by Bash
Words like if, for, while, and done are reserved words in the language. Bash still accepts them as variable names, because the shell reads them as ordinary text when they appear before an equals sign:
if=3
echo "if=$if"
if=3
Even though it works, it makes the script confusing to read, so avoid reusing these words. The same holds for the names of commands. A variable called echo does not stop the echo command from working, but it leaves readers puzzled:
echo=5
echo "value of echo var: $echo"
echo hi
value of echo var: 5
hi
Checking Whether a Name Is Valid
When a script builds variable names from user input or from a file, it should check them first. A regular expression inside [[ ]] expresses the three rules in one line. The pattern says: start with a letter or underscore, then allow any number of letters, digits, or underscores.
is_valid_name() {
[[ $1 =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]
}
for candidate in count _tmp MAX_SIZE 2fast my-var "a b" ""; do
if is_valid_name "$candidate"; then
echo "valid: '$candidate'"
else
echo "invalid: '$candidate'"
fi
done
valid: 'count'
valid: '_tmp'
valid: 'MAX_SIZE'
invalid: '2fast'
invalid: 'my-var'
invalid: 'a b'
invalid: ''
The =~ operator tests the text against the pattern. The function returns success (0) for a match and failure for everything else, so it can sit directly in an if. The empty string is rejected because the pattern requires at least one character.
Creating a Variable Whose Name Is Stored in Another Variable
Sometimes the name itself must come from a variable. The printf -v option writes a formatted result straight into the variable you name, and it validates the name for you:
varname="dyn_var"
printf -v "$varname" '%s' "hello"
echo "$dyn_var"
hello
Dynamic names like this are an advanced technique. Where possible, an associative array (covered in a later lesson) is clearer.
Non-ASCII Characters in Names
The rules above refer to ASCII letters. Whether a letter such as ï is accepted in a name depends on the system's locale settings. In a test with the default C locale, a name with an accented character was rejected as a command. For portable scripts, use only the ASCII letters, digits, and underscores.
Listing Your Own Variables
The compgen -A variable command lists the names of all variables in the shell. Combined with grep it finds those that share a prefix, which is one more reason why a consistent naming prefix is handy:
APP_NAME=demo
APP_PORT=8080
compgen -A variable | grep '^APP_' | sort
APP_NAME
APP_PORT
Using one prefix for related settings, such as APP_ here, keeps them easy to find and avoids clashing with the names Bash and other programs define.