Rules for Naming Bash Variables

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 35 of 205

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:

  1. It may contain only ASCII letters (a to z, A to Z), digits (0 to 9), and underscores (_).
  2. It must not start with a digit.
  3. 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:

  • 1abc starts with a digit.
  • my-var contains a hyphen, which Bash reads as part of a command name, not as a variable character.
  • my var=5 contains a space, so the first word is my, which is not a command.
  • my.var contains 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, and BACKUP_DIR.
  • Use lowercase, with underscores between words, for ordinary variables in a script, such as file_count or input_name.
  • Choose descriptive names. backup_dir explains itself, while bd does 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:

NameWhat it holds
PATHDirectories searched for commands
HOMEThe user's home directory
IFSThe characters used for word splitting
PS1The text of the interactive prompt
RANDOMA new random number on each read
SECONDSThe seconds since the shell started
LINENOThe current line number in the script
UID, EUIDThe 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Rules for Naming Bash Variables and get answers drawn from it.

Signed-in readers only.