How-To Geek

How to work with variables in bash.

Want to take your Linux command-line skills to the next level? Here's everything you need to know to start working with variables.

Hannah Stryker / How-To Geek

Quick Links

Variables 101, examples of bash variables, how to use bash variables in scripts, how to use command line parameters in scripts, working with special variables, environment variables, how to export variables, how to quote variables, echo is your friend, key takeaways.

  • Variables are named symbols representing strings or numeric values. They are treated as their value when used in commands and expressions.
  • Variable names should be descriptive and cannot start with a number or contain spaces. They can start with an underscore and can have alphanumeric characters.
  • Variables can be used to store and reference values. The value of a variable can be changed, and it can be referenced by using the dollar sign $ before the variable name.

Variables are vital if you want to write scripts and understand what that code you're about to cut and paste from the web will do to your Linux computer. We'll get you started!

Variables are named symbols that represent either a string or numeric value. When you use them in commands and expressions, they are treated as if you had typed the value they hold instead of the name of the variable.

To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore. Apart from that, you can use any mix of upper- and lowercase alphanumeric characters.

Here, we'll create five variables. The format is to type the name, the equals sign = , and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.

We'll create four string variables and one numeric variable,





To see the value held in a variable, use the echo command. You must precede the variable name with a dollar sign $ whenever you reference the value it contains, as shown below:

echo $my_name

echo $my_boost

echo $this_year

Let's use all of our variables at once:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year"

The values of the variables replace their names. You can also change the values of variables. To assign a new value to the variable, my_boost , you just repeat what you did when you assigned its first value, like so:


If you re-run the previous command, you now get a different result:

So, you can use the same command that references the same variables and get different results if you change the values held in the variables.

We'll talk about quoting variables later. For now, here are some things to remember:

  • A variable in single quotes ' is treated as a literal string, and not as a variable.
  • Variables in quotation marks " are treated as variables.
  • To get the value held in a variable, you have to provide the dollar sign $ .
  • A variable without the dollar sign $ only provides the name of the variable.

You can also create a variable that takes its value from an existing variable or number of variables. The following command defines a new variable called drink_of_the_Year, and assigns it the combined values of the my_boost and this_year variables:

drink_of-the_Year="$my_boost $this_year"

echo drink_of_the-Year

Scripts would be completely hamstrung without variables. Variables provide the flexibility that makes a script a general, rather than a specific, solution. To illustrate the difference, here's a script that counts the files in the /dev directory.

Type this into a text file, and then save it as (for "file count"):

#!/bin/bashfolder_to_count=/devfile_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

Before you can run the script, you have to make it executable, as shown below:

chmod +x

Type the following to run the script:

This prints the number of files in the /dev directory. Here's how it works:

  • A variable called folder_to_count is defined, and it's set to hold the string "/dev."
  • Another variable, called file_count , is defined. This variable takes its value from a command substitution. This is the command phrase between the parentheses $( ) . Note there's a dollar sign $ before the first parenthesis. This construct $( ) evaluates the commands within the parentheses, and then returns their final value. In this example, that value is assigned to the file_count variable. As far as the file_count variable is concerned, it's passed a value to hold; it isn't concerned with how the value was obtained.
  • The command evaluated in the command substitution performs an ls file listing on the directory in the folder_to_count variable, which has been set to "/dev." So, the script executes the command "ls /dev."
  • The output from this command is piped into the wc command. The -l (line count) option causes wc to count the number of lines in the output from the ls command. As each file is listed on a separate line, this is the count of files and subdirectories in the "/dev" directory. This value is assigned to the file_count variable.
  • The final line uses echo to output the result.

But this only works for the "/dev" directory. How can we make the script work with any directory? All it takes is one small change.

Many commands, such as ls and wc , take command line parameters. These provide information to the command, so it knows what you want it to do. If you want ls to work on your home directory and also to show hidden files , you can use the following command, where the tilde ~ and the -a (all) option are command line parameters:

Our scripts can accept command line parameters. They're referenced as $1 for the first parameter, $2 as the second, and so on, up to $9 for the ninth parameter. (Actually, there's a $0 , as well, but that's reserved to always hold the script.)

You can reference command line parameters in a script just as you would regular variables. Let's modify our script, as shown below, and save it with the new name :

#!/bin/bashfolder_to_count=$1file_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

This time, the folder_to_count variable is assigned the value of the first command line parameter, $1 .

The rest of the script works exactly as it did before. Rather than a specific solution, your script is now a general one. You can use it on any directory because it's not hardcoded to work only with "/dev."

Here's how you make the script executable:

chmod +x

Now, try it with a few directories. You can do "/dev" first to make sure you get the same result as before. Type the following:

./ /dev

./ /etc

./ /bin

You get the same result (207 files) as before for the "/dev" directory. This is encouraging, and you get directory-specific results for each of the other command line parameters.

To shorten the script, you could dispense with the variable, folder_to_count , altogether, and just reference $1 throughout, as follows:

#!/bin/bash file_count=$(ls $1 wc -l) echo $file_count files in $1

We mentioned $0 , which is always set to the filename of the script. This allows you to use the script to do things like print its name out correctly, even if it's renamed. This is useful in logging situations, in which you want to know the name of the process that added an entry.

The following are the other special preset variables:

  • $# : How many command line parameters were passed to the script.
  • $@ : All the command line parameters passed to the script.
  • $? : The exit status of the last process to run.
  • $$ : The Process ID (PID) of the current script.
  • $USER : The username of the user executing the script.
  • $HOSTNAME : The hostname of the computer running the script.
  • $SECONDS : The number of seconds the script has been running for.
  • $RANDOM : Returns a random number.
  • $LINENO : Returns the current line number of the script.

You want to see all of them in one script, don't you? You can! Save the following as a text file called, :

#!/bin/bashecho "There were $# command line parameters"echo "They are: $@"echo "Parameter 1 is: $1"echo "The script is called: $0"# any old process so that we can report on the exit statuspwdecho "pwd returned $?"echo "This script has Process ID $$"echo "The script was started by $USER"echo "It is running on $HOSTNAME"sleep 3echo "It has been running for $SECONDS seconds"echo "Random number: $RANDOM"echo "This is line number $LINENO of the script"

Type the following to make it executable:

chmod +x

Now, you can run it with a bunch of different command line parameters, as shown below.

Bash uses environment variables to define and record the properties of the environment it creates when it launches. These hold information Bash can readily access, such as your username, locale, the number of commands your history file can hold, your default editor, and lots more.

To see the active environment variables in your Bash session, use this command:

If you scroll through the list, you might find some that would be useful to reference in your scripts.

When a script runs, it's in its own process, and the variables it uses cannot be seen outside of that process. If you want to share a variable with another script that your script launches, you have to export that variable. We'll show you how to this with two scripts.

First, save the following with the filename :

#!/bin/bashfirst_var=alphasecond_var=bravo# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"export first_varexport second_var./ check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This creates two variables, first_var and second_var , and it assigns some values. It prints these to the terminal window, exports the variables, and calls . When terminates, and process flow returns to this script, it again prints the variables to the terminal window. Then, you can see if they changed.

The second script we'll use is . This is the script that calls. Type the following:

#!/bin/bash# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"# set new valuesfirst_var=charliesecond_var=delta# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This second script prints the values of the two variables, assigns new values to them, and then prints them again.

To run these scripts, you have to type the following to make them executable:

chmod +x script_one.shchmod +x

And now, type the following to launch :


This is what the output tells us:

  • prints the values of the variables, which are alpha and bravo.
  • prints the values of the variables (alpha and bravo) as it received them.
  • changes them to charlie and delta.
  • prints the values of the variables, which are still alpha and bravo.

What happens in the second script, stays in the second script. It's like copies of the variables are sent to the second script, but they're discarded when that script exits. The original variables in the first script aren't altered by anything that happens to the copies of them in the second.

You might have noticed that when scripts reference variables, they're in quotation marks " . This allows variables to be referenced correctly, so their values are used when the line is executed in the script.

If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter.

Here's an example:

site_name=How-To Geek

Bash sees the space before "Geek" as an indication that a new command is starting. It reports that there is no such command, and abandons the line. echo shows us that the site_name variable holds nothing — not even the "How-To" text.

Try that again with quotation marks around the value, as shown below:

site_name="How-To Geek"

This time, it's recognized as a single value and assigned correctly to the site_name variable.

It can take some time to get used to command substitution, quoting variables, and remembering when to include the dollar sign.

Before you hit Enter and execute a line of Bash commands, try it with echo in front of it. This way, you can make sure what's going to happen is what you want. You can also catch any mistakes you might have made in the syntax.

  • Shell Scripting
  • Docker in Linux
  • Kubernetes in Linux
  • Linux interview question

assign bash variable

  • Explore Our Geeks Community
  • Setting Up Standard Linux File Systems and Configuring NFSv4 Server
  • How to Exclude Certain Paths With the find Command in Linux
  • How use Nmon and "Java Nmon Analyzer" for Monitor Linux Performance
  • Brute Force Attack in Metasploit
  • Auditd Tool for Security Auditing on Linux Server
  • Difference Between a Script file and a Binary file
  • Tiger – The Unix Security Audit and Intrusion Detection Tool
  • Reporting Tools in Kali Linux
  • Rename Files and Remove Shell PID as extension Using Bash
  • How to Configure Multipathing in Linux?
  • eXtern OS – JavaScript and NodeJS based Linux Distribution
  • Social Engineering Techniques in Metasploit
  • Create a Log File in PowerShell Script
  • Router Vulnerabilities in Kali Linux
  • How to set the environmental variable LD_LIBRARY_PATH in Linux
  • How to Check If a Linux Kernel Supports My System Devices
  • NTP Configuration in CentOS
  • How to configure network interfaces in CentOS?
  • How To Copy Command Output To Linux Clipboard Directly

Set – $VARIABLE” in bash

In the world of bash scripting, you may come across the phrase “set – $VARIABLE”. But what does it mean?

At its most basic, “set – $VARIABLE” is used to split the value of a bash variable into separate words, using the Internal Field Separator (IFS) as the delimiter. For example, if VARIABLE has the value “a b c”, then running “set – $VARIABLE” would set the positional parameters to “a”, “b”, and “c”.

This may not seem particularly useful at first glance, but it can be a powerful tool when used in the right context. One common use case is to process command-line arguments passed to a bash script. When you run a bash script, the positional parameters (i.e., $1, $2, etc.) represent the arguments passed to the script. By using “set – $VARIABLE”, you can easily split a single argument into multiple words, allowing you to process them more easily.

Here’s an example of how this might be used:

assign bash variable

If you save this script as “” and run it like this:

assign bash variable

 Loop over the elements of a list stored in a variable

Another common use case for “set – $VARIABLE” is to loop over the elements of a list stored in a variable. For example:

assign bash variable

It’s worth noting that “set – $VARIABLE” only works if the value of VARIABLE is a single string. If VARIABLE is an array, you’ll need to use a different approach. One option is to use the “printf ‘%s\n’ “${VARIABLE[@]}” syntax, which expands the array into a series of separate words, each separated by a new line character.

assign bash variable

In conclusion, “set – $VARIABLE” is a useful bash feature that allows you to split the value of a variable into separate words, using the IFS as the delimiter. It can be used to process command-line arguments or to loop over the elements of a list stored in a variable. While it only works with single strings, there are alternative approaches that can be used with arrays. Understanding how “set – $VARIABLE” works and when to use it can be a valuable addition to your bash scripting toolkit.

Please Login to comment...


  • Technical Scripter 2022
  • Technical Scripter

Please write us at [email protected] to report any issue with the above content

Improve your Coding Skills with Practice



How to Assign Variable in Bash

  • Bash Scripting

bash variable-assignment

A variable is a named storage location in a program's memory where a value can be stored, retrieved, and manipulated. Like any programming language, Variables are an essential component in the Bash scripts. They allow you to create dynamic scripts that can change based on the data that is passed to them.

In Bash, there are different ways to assign variables which will be covered in detail.

Local vs Global variable assignment

Bash has two types of variables - local, and global based on the scope where they are defined in the script.

Local variable

A local variable is a variable that is defined within a function or a block of code and can only be accessed within that function or block. Local variables are only accessible within the function or block in which they are defined and the value of the variable is lost once the function or the block ends.

Global variable

A global variable, on the other hand, is a variable that is defined outside of any function or block and can be accessed from any part of the program. Global variables are accessible from anywhere in the program, including from within functions and blocks.

See the following script to understand the scope and lifetime of local vs global variables:

In the script:

  • num=2 initializes the global num variable.
  • local num=1 declared inside the function demo_local_va r block initializes the local num variable whose scope is within the function only
  • Outside this function, echoing $num always prints the value of global num variable.

Local vs Global variable

Single variable assignment

In bash, a single variable can be assigned simply using the syntax

with no space before and after the `=` sign. You do not need to declare the data type in bash while assigning a variable.

Integer assignment

To assign an integer to a variable, you can use the following syntax:

In the script, num=1 assigns a global integer variable value 1.

integer variable assignment

String assignment

There are multiple ways to assign strings:

  • Single words can be assigned directly without any quotes.
  • Multi-word strings can be defined using Single quotes (') and Double quotes (").

However, there is a difference between how Bash interprets single quotes and double quotes.

When you use single quotes to define a string, it preserves the literal value of each character. On the other hand, if you use double quotes, it recognizes the special symbols ($, `, \) and expands the strings using the shell expansion rules.

In this example,

  • greeting2 treats $name as a string and thus it gets expanded to Hello $name .
  • While greeting3 expands $name to world , thus generating the string - Hello world .

string variable assignment

Boolean assignment

To assign a boolean value to a variable, you can use the following syntax:

  • true_val=true and false_val=false initializes the boolean variables.
  • We can use these booleans in conditional statements to make decisions.

boolean variable assignment

Multi-variable assignments

Bash provides a straightforward syntax for assigning multiple variables in a single line as follows:

multiple variable assignment

In the above script, a=1, b=2, c=3 initializes three integer variables using a single statement.

Default value assignment

Bash has a built-in syntax for providing default values to the variables:-

If var is not defined, it assigns the defaultval to the newVar.

See the following script to see how default assignments work:

  • In the first example, echo $userOutput1 prints 5 to the stdout since var1 is defined.
  • In the second example, echo $userOutput2 prints var2 is not defined since var2 is not defined before.

assign default value to the variable

Using let command for assignments

The let command is used to assign numeric values to the variables and perform arithmetic, bitwise, and logical operations.

Consider the following script:

assign numeric values to the variables using let

let command is an important utility which provides a simplistic syntax to perform a variety of arithmetic, logical and bitwise operations.

Using Read command

Bash has a built-in read command that can read a line from the standard input (stdin) and split the line into multiple variables.

See the following script to understand how the read command works:

read into multiple variables

In the script read animal color accepts 2 inputs from the user and stores them in the variables animal and color .

Read command also comes with some useful options:

Prompt flag (-p) helps to provide a useful text to the user and accept inputs. This removes the additional need for echo statements simplifying the code.

Silent flag (-s) helps the user to hide the input from display. This is useful when entering sensitive information such as passwords.

  • Input to array

Array (-a) flag reads the input to an array instead of individual words.

  • read -p “Enter the username: “   prints the text “Enter the username: “ and also accepts an input from the user.
  • read -s -p “Enter the password: “   accepts an input from the user in silent mode, i.e. it is not displayed on the screen.
  • read -p “Enter your hobbies(space separated): “ -a hobbies accepts an array input from the user into hobbies variable. The variable can then be iterated over using the array iteration syntax.

assign bash variable

  • Bash supports both local and global variables. Using global variables, in general should be avoided since they increase the complexity of the code and may introduce hard to debug bugs.
  • Bash provides built-in support for assigning integer, strings and boolean type variables. Data type is not required while assigning variables.
  • Multiple variables can be assigned simply by defining multiple variables in a single line.
  • Bash also supports initializing variables with default values. This is a good programming practice and helps to avoid bugs due to uninitialized variables.
  • The let command is a useful built-in in bash for working with numerics and performing a variety of operations.
  • The read command is another important built-in to read input from the command line and create interactive applications.

If this resource helped you, let us know your care by a Thanks Tweet. Tweet a thanks


Sorry about that.

About The Author

Madhur batra.

Madhur Batra

Madhur Batra is a highly skilled software engineer with 8 years of personal programming experience and 4 years of professional industry experience. He holds a B.E. degree in Information Technology from NSUT, Delhi. Madhur's expertise lies in C/C++, Python, Golang, Shell scripting, Azure, systems programming, and computer networking. With a strong background in these areas, he is well-equipped to tackle complex software development projects and contribute effectively to any team.

What is Shell in Linux

Check Which Shell You are Using on Linux

Script to Check Linux Server Health

Types of Shells in Linux

Pass all Arguments in Bash Scripting

Concatenate String Variables in Bash [Join Strings]

How to Do Bash Variable Substitution

Bash Parameter Expansion with Cheat Sheet

Create Multiline Strings in Bash

Bash Division Explained

Bash Loop Through Lines in a File

How to Use While Loop in Bash

Bash for Loop Range Variable

Bash If Else Statements: Examples and Syntax

How to Read CSV File in Bash

Leave a Reply

Leave a comment cancel reply.


  1. Bash Script: define las variables Bash y sus tipos

    assign bash variable

  2. Sql Statement Table Alias Example Bash Script

    assign bash variable

  3. How to use Variables in Bash

    assign bash variable

  4. Assign to a bash array variable indirectly, by dynamically constructed variable name

    assign bash variable

  5. [Solved] How do I assign a value to a BASH variable iff

    assign bash variable

  6. How to Assign Output of a Linux Command to a Variable

    assign bash variable


  1. The Linux GPS

  2. assign variable in c program #cprogramming #coding #cprogrammingvideo #tutorial

  3. Unix: Cut command stored in variable will not work

  4. How to Create Varibale in Sratch


  6. How to get values for variables from a source file using Bash Script on Rocky Linux 9.2


  1. What Is a Qualitative Variable?

    Qualitative variables are those with no natural or logical order. While scientists often assign a number to each, these numbers are not meaningful in any way. Examples of qualitative variables include things such as color, shape or pattern.

  2. What Is the Meaning of Experimental Research?

    In experimental research, researchers use controllable variables to see if manipulation of these variables has an effect on the experiment’s outcome. Additionally, subjects of the experimental research are randomly assigned to prevent bias ...

  3. What Is a Mixed Design in Psychology?

    Mixed designs make use of already-present variables and manipulate a second variable. This is also referred to as a quasi-experimental or natural design. Subjects are not randomly assigned to groups; they automatically fall into one of thos...

  4. 4.2. Variable Assignment

    #!/bin/bash # Naked variables echo # When is a variable "naked", i.e., lacking the '$' in front? # When it is being assigned, rather than referenced.

  5. How to Work with Variables in Bash

    If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by

  6. Set

    At its most basic, “set – $VARIABLE” is used to split the value of a bash variable into separate words, using the Internal Field Separator (IFS)

  7. BASH Programming

    There are no data types. A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a

  8. Bash Variable Assignment

    echo "$var_1 is the best." echo "However, you can try $var_2." echo "Or else you may use $var_3." echo "In case you are a beginner

  9. How to Assign Default Value to a Variable Using Bash

    If a variable, x, is unset or is the null string, then ${x:-default_value} expands to the default_value string. Importantly, no assignment to

  10. How to Assign Variable in Bash

    Conclusion · Bash supports both local and global variables. · Bash provides built-in support for assigning integer, strings and boolean type

  11. Bash Assign Output of Shell Command To Variable

    Bash Assign Output of Shell Command To And Store To a Variable ... Do not put any spaces after the equals sign and command must be on right side

  12. How to assign the result of an expression to a variable in bash

    How to assign the result of an expression to a variable in bash · country_code: · | jq · country_name: · | jq · | jq · cc: · cn=$( · ) echo

  13. Defining a Bash Variable With or Without 'export'

    The first definition creates a variable named MYVAR and assigns it the value 1729. This is a shell variable. The second definition with the

  14. Assigning a command to variable

    You can't stuff a command into a string like this. To define a short name for a command, use an alias (if the command is complete) or a function