Bash Variable Naming Conventions in Shell Scripts [6 Rules] (2023)

Lal»Bash scripting tutorial»bash variables»Variable declaration and assignment»Bash Variable Naming Conventions in Shell Scripts [6 Rules]

script bash

Muhammad Xia Milan

August 2, 2023

When writing shell scriptshit hard, choosing an appropriate name for the variable is criticalthe code readabilityemaintainability. by being consistentnaming convention, you can improve the clarity and understandability of your script by making it easier to understand.debuggingeAdjustment. This article will list some rules for Bash variable naming conventionsshell script

index expansion

main conclusion

  • Learn Bash variable naming conventions.
  • Create your own variable names using the provided material.
  • Assignments that test your understanding of variable naming conventions.

free download

Download exercise files

6 Different Bash Variable Naming Conventions in Shell Scripts

In order to build comprehensive and easy-to-understand code, it is crucial to name variables in the correct direction. This also allows you to avoid any unexpected errors during executiondebuggingspeed.

althoughhit hardNo strict naming conventions are enforced, and developers typically follow certain conventions to improve code clarity and consistency. Below I discusssix different rulesThis must be followed when choosing variable names.

Rule 01: Use letters and numbers to name variables

althoughalphabetCommonly used in variable names, includingnumberCan add a level of specificity and clarity to your code. However,script bashIt is auppercase and lowercaselanguage, which means you can use different combinations of cases to store different data in the same variable.

Steps to follow >

❶ First, start afree terminal

❷ Write the following command to open the fileNano:



  • Nano:Open the file in the Nano text editor.
  • file name.

❸ Copy the script mentioned below:

#!/bin/bash#Use only letters to name variables var=35#Using UppercaseVAR="Var variables contain uppercase letters" #Use letters and numbers to name variables var123=34.4echo $varecho $VARecho $var123


first row#!/bin/bashSpecifies the interpreter to use (/bin/bash) to run the script. So there are three variablesera,era, evariable 123Created to store some data in it. later,echo commandUsed to print their stored values ​​to demonstrate that all of these variables are named correctly and conform to bash script naming conventions.

❹ pressureCTRL+Oeentersave document;control key+Xexit.

❺ Make the file executable with:

chmod u+x


  • chmod: Used to change the permissions of files and directories.
  • you+x: here,youRefers"from user" orownerfile and+xSpecify the permissions to add, in this case "implement"Allowed. Whenyou+xAdded to the file permissions it grants the user (owner) file execution permissions (running) document.
  • is the name of the file to apply the permission to.

❻ Run the script with the following command:


Bash Variable Naming Conventions in Shell Scripts [6 Rules] (2)In the image above, you can see that all three variables have returned their respective values:35,VAR variable contains capital letters, e34,4

Rule 02: Avoid using numbers at the beginning of variable names

when it comes to variable namingshell impactscripts, an important convention to follow is to avoid usingnumberas the first character of the variable name. Below is an example where I create multiple variables by putting numbers at the beginning and end of the variable names. Variables that start with a number do not return a corresponding value at runtime.

You can followRule Step 01, save the script and make the script executable.

Script ( >

#!/bin/bash#The variable starts with a number (invalid form) 123var="Wrong naming method" #Correct form var123="Correct naming" echo $123varecho $var123


here,#! /bin/bash: '#!', calledShebangorhash explosion. he pointed outInterpretersfor running the script, in this case thethe party. then the random variable123varis created by prepending the digits of the numbers. other variablesvariable 123It is also named to show the correct way of naming. later,echo commandDisplays the corresponding value contained in the variable.

Bash Variable Naming Conventions in Shell Scripts [6 Rules] (3)as123varNot the correct way to name it, an error occurred in the variable. but thatecho commandSuccessfully displayed "correct nomenclature" string does not containvariable 123Changing.

Rule 03: Use underscores to avoid spaces

If the variable name containsmultiple words, it is recommended to separate them usingunderlined(_). For example,usernameIt is recommended to useusername

You can followRule Step 01, save the script and make the script executable.

Script (>

#!/bin/bash#Wrong method of variable naming var name="jhon"#Correct method of variable naming var_name="Tom" echo $var nameecho $var_name


oxygen#!/bin/bashit's knownShebang, and specifyInterpreters(in this case,/bin/bash) should be used to run the script. Next,variable nameCreate a variable and try to useecho command. Likewise, anothervariable nameCreate variable to store string in it and display it later.

Bash Variable Naming Conventions in Shell Scripts [6 Rules] (4)As you can see in the image above, onlyvariable namevariable returns yourKedacourage"tom"at runtime.

Rule 04: The assignment operator (=) must not have spaces on either side

When using this operator, it is recommended not to usespace(space or tab) immediately before or after the operator. The interpreter understands this asOrderreplaceassignmentOtherwise it is a variable. Below is a related example.

You can followRule Step 01, save the script and make the script executable.

Screenplay ( >

#!/bin/bash#Wrong way to declare data allocation var1 =23var2= 25#Correct way var3="Great"#print variablesecho $var1echo $var2echo $var3


here,#! /bin/bash: '#!', calledShebangorhash explosion. he pointed outInterpretersfor running the script, in this case thethe party. so a variablevariable 1After creation, followed by a spacevariable 1. For the second variable,variable 2, followed by a spaceequal sign. Both of these cases are false, so a runtime error occurs. Later another variablevariable 3is correctly created and then displaysecho command

Bash Variable Naming Conventions in Shell Scripts [6 Rules] (5)The output image shows onlyvariable 3variable returns its string value "Excellent" at runtime.

Rule 05: Avoid special characters (except underscore)

In general, it is best to followalphanumeric charactersCardenumber) eunderlinedwhen naming variables. avoid usingSpecial characters,space, orpunctuationtags, as they may cause syntax errors or introduce unexpected behavior. For example, using anySpecial charactersas@、$、or#It is illegal to declare variables anywhere.

You can followRule Step 01, save the script and make the script executable.

Screenplay ( >

#!/bin/bash#Wrong variable naming method var@=5var#=8var$=23#Display variable data echo $var@echo $var#echo $var$#Correct naming method arvar=45echo $var


here,#! /bin/bash: '#!', calledShebangorhash explosion. he pointed outInterpretersfor running the script, in this case thethe party. Next, create three different variables with special characters, e.g.@、#、$。Next, allthreevariable is called usingecho commandDisplay your personal data. Then there is a variableeraIt can also be created and displayed using the following commandsecho command

Bash Variable Naming Conventions in Shell Scripts [6 Rules] (6)This picture shows@、#、$such as wrong exports and45as the correct output.

Rule 06: Avoid embedding reserved keywords or command names as variable names

hit hardThere is a set of reserved keywords that have special meanings and functions within the shell. To avoid conflicts and unexpected behavior when you fetch variable data, it is critical to avoid using these reserved keywords as variable names. Examples of reserved keywords includeand,other,case,to do,although,ETC。

You can followRule Step 01, save the script and make the script executable.

Script ( >

#!/bin/bash#Wrong variable naming method while=56if=34elif=67#Display variable value echo $whileecho $ifecho $elif#Correct variable naming method=50echo $variable


here,#! /bin/bash: '#!', calledShebangorhash explosion. he pointed outInterpretersfor running the script, in this case thethe party. Some reserved words, such asalthough,and,Elifetc. store data in this code. then it usesecho command

Bash Variable Naming Conventions in Shell Scripts [6 Rules] (7)The figure above shows all four variablesalthough,and,Elif, eerareturn their respective stored values56,34,67, e50

A comparison of correct and incorrect variable naming conventions

draw one lastDiscussion summaryDescribe allowed and disallowed variable naming in a table. Check out this for an overview.

correct naming conventionincorrect naming convention
Use lowercase letters and underscores.Start with a number or a special character (except underscore).
Start with a letter or underscore.Contains spaces or special characters such as !, @, #, %, etc.
It consists of lowercase letters, underscores, and numbers.Use capital letters.
The name can contain numbers and underscores (except the first character).Merge reserved keywords or builtin command names into variable names.
Use descriptive and meaningful names.Using inconsistent or ambiguous names can impair code readability.

Assignments in Bash variable naming conventions

Here I also made a list of tasks for my practice. Don't forget to share your answers in the comments section.

  1. useuppercase letterLetters in variable names are acceptable. (Real or fake)
  2. we can usehe is a fanVariable names in (-)hit hard. (Real or fake)
  3. Bash is case sensitive, soMinhawaleMinhawalare treated as different variables. (Real or fake)
  4. We can use spaces in variable names in Bash. (Real or fake)
  5. Variable names can containSpecial charactersJust like !, @ and # in Bash. (Real or fake)
  6. Provide a valid Bash variable name, includinguppercase letterelower caseletters, andunderlined
  7. DecideandThe following variable names arecorrectorNo:
  • my variable
  • 123abc
  • username
  • my variable
  • Minhawal
  • Min Hawal!

in conclusion

In short, as should bevariable naming conventionis critical when working withbash variablesin a shell script. In this article, I have tried to provide some mandatory rules to follow when choosing variable names. If you remember, things will be easy, but if you have any doubts about this article. Comments are welcome below. Thanks.

people also ask

How to name variables in bash script?

name the variable in ascript bash, you can use any combination ofCard,number, eunderlined. Variable names must start with acharteror aunderlined, That iscaseTop secret

How to set variable names in Bash?

To set variables in Bash, you can usevariable name = valuesyntax. There can be no spaces before and after the variable nameequal sign, the value can beKeda,number, or any other validtype of dataThey are bash.

What is $1 in a bash script?

In a Bash script,1Refers to the first command-line argument passed to the script. when you run ascript bashand provide arguments, scripts can access them using special variables starting at1represents the first parameter,2 USDAnd so on for the second argument.

What are variable types in bash?

emhit hard, the variable has no explicit type. they were treated likedefaults to string. Bash does not enforce strict typing, allowing you to assign and manipulate values ​​of different types (for example,number,rope) in the same variable.

rate this article


Top Articles
Latest Posts
Article information

Author: Carlyn Walter

Last Updated: 06/01/2024

Views: 5886

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Carlyn Walter

Birthday: 1996-01-03

Address: Suite 452 40815 Denyse Extensions, Sengermouth, OR 42374

Phone: +8501809515404

Job: Manufacturing Technician

Hobby: Table tennis, Archery, Vacation, Metal detecting, Yo-yoing, Crocheting, Creative writing

Introduction: My name is Carlyn Walter, I am a lively, glamorous, healthy, clean, powerful, calm, combative person who loves writing and wants to share my knowledge and understanding with you.