How-To Geek

How to work with variables in bash.

4

Your changes have been saved

Email is sent

Email has already been sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

Hannah Stryker / How-To Geek

Quick Links

What is a variable in bash, 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,

my_name=Dave

my_boost=Linux

his_boost=Spinach

this_year=2019

Defining variables in Linux.

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

Using echo to display the values held in variables in a terminal window

Let's use all of our variables at once:

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

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year" in a terminal window

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:

my_boost=Tequila

my_boost=Tequila in a terminal window

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

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

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.

Correct an incorrect examples of referencing variables in a terminal window

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

drink_of-the_Year="$my_boost $this_year" in a terminal window

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 fcnt.sh (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 fcnt.sh

chmod +x fcnt.sh in a terminal window

Type the following to run the script:

./fcnt.sh in a terminal window

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 fcnt2.sh :

#!/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 fcnt2.sh

chmod +x fcnt2.sh in a terminal window

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:

./fnct2.sh /dev

./fnct2.sh /etc

./fnct2.sh /bin

./fnct2.sh /dev in a terminal window

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, special.sh :

#!/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 special.sh

fig13 in a terminal window

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

./special.sh alpha bravo charlie 56 2048 Thursday in a terminal window

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:

env | less in a terminal window

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

List of environment variables in less in a terminal window

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 script_one.sh :

#!/bin/bashfirst_var=alphasecond_var=bravo# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"export first_varexport second_var./script_two.sh# 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 script_two.sh . When script_two.sh 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 script_two.sh . This is the script that script_one.sh 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 script_two.sh

chmod +x script_one.sh in a terminal window

And now, type the following to launch script_one.sh :

./script_one.sh

./script_one.sh in a terminal window

This is what the output tells us:

  • script_one.sh prints the values of the variables, which are alpha and bravo.
  • script_two.sh prints the values of the variables (alpha and bravo) as it received them.
  • script_two.sh changes them to charlie and delta.
  • script_one.sh 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

site_name=How-To Geek in a terminal window

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"

site_name="How-To Geek" in a terminal window

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.

Linux Commands

Files

Processes

Networking

  • Linux & macOS Terminal

LinuxSimply

Home > Bash Scripting Tutorial > Bash Variables > Variable Declaration and Assignment

Variable Declaration and Assignment

Mohammad Shah Miran

In programming, a variable serves as a placeholder for an unknown value, enabling the user to store the different data and access them whenever needed. During compilation or interpretation , the symbolic names of variables are replaced with their corresponding data locations . This article will mainly focus on the variable declaration and assignment in a Bash Script . So, let’s start.

Table of Contents

Key Takeaways

  • Getting familiar with Bash Variables.
  • Learning to declare and assign variables.

Free Downloads

Factors of variable declaration and assignment.

There are multiple factors to be followed to declare a variable and assign data to it. Here I have listed the factors below to understand the process. Check it out.

1. Choosing Appropriate Variable Name

When choosing appropriate variable names for declaration and assignment, it’s essential to follow some guidelines to ensure clarity and readability and to avoid conflicts with other system variables. Here some common guidelines to be followed are listed below:

  • Using descriptive names: Using descriptive names in variable naming conventions involves choosing meaningful and expressive names for variables in your code. This practice improves code readability and makes it easier to grasp the purpose of the code at a glance.
  • Using lowercase letters: It is a good practice to begin variable names with a lowercase letter . This convention is not enforced by the bash language itself, but it is a widely followed practice to improve code readability and maintain consistency . For example name , age , count , etc.
  • Separating words with underscores: Using underscores to separate words in variable names enhances code readability. For example first_name , num_students , etc.
  • Avoid starting with numbers: Variable names should not begin with a number. For instance, 1var is not a valid variable
  • Avoiding special characters : Avoid using special characters , whitespace , or punctuation marks, as they can cause syntax errors or introduce unexpected behavior. For instance, using any special character such as @, $, or # anywhere while declaring a variable is not legal.

2. Declaring the Variable in the Bash Script

In Bash , declaring variables and assigning values to them can be done for different data types by using different options along with the declare command . However, you can also declare and assign the variable value without explicitly specifying the type .

3. Assigning the Value to the Variable

When declaring variables for numeric values , simply assign the desired number directly, as in age=30 for an integer or price=12.99 for a floating – point value . For strings , enclose the text in single or double quotes , such as name =’ John ‘ or city =” New York “. Booleans can be represented using 0 and 1 , where 0 indicates false and 1 represents true , like is_valid = 1 .

Arrays are declared by assigning a sequence of values enclosed in parentheses to a variable, e.g., fruits=(“apple” “banana” “orange”) . To create associative arrays ( key-value pairs ), use the declare -A command followed by assigning the elements, like declare -A ages=([“John”]=30 [“Jane”]=25) .

4 Practical Cases of Declaring and Assigning Bash Variable

In this section, I have demonstrated some sample Bash scripts that will help you understand the basic concept of variable declaration and assignment in Bash script . So let’s get into it.

Case 01: Basic Variable Assignment in Bash Script

In my first case , I have shown a basic variable assignment with its output. Here, I have taken a string and an integer variable to show the basic variable assignment mechanism. Follow the given steps to accomplish the task.

Steps to Follow >

❶ At first, launch an Ubuntu terminal .

❷ Write the following command to open a file in Nano :

  • nano : Opens a file in the Nano text editor.
  • basic_var.sh : Name of the file.

❸ Copy the script mentioned below:

The script starts with the shebang line ( #!/bin/bash ), specifying that the script should be executed using the Bash shell . Next, two variables are declared and assigned values using the format variable_name = value . The first variable is name , and it is assigned the string value “ John .” The second variable is age , assigned the numeric value 30 . The script then uses the echo command to print the values of the variables.

❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.

❺ Use the following command to make the file executable:

  • chmod : is used to change the permissions of files and directories.
  • u+x : Here, u refers to the “ user ” or the owner of the file and +x specifies the permission being added, in this case, the “ execute ” permission. When u+x is added to the file permissions, it grants the user ( owner ) permission to execute ( run ) the file.
  • basic_var.sh : File name to which the permissions are being applied.

❻ Run the script by the following command:

Basic Variable Assignment in Bash Script

Case 02: Input From User and Variable Assignment

In Bash , you can take input from the user and store it in variables using the read command . To do so use the following script:

You can follow the steps of Case 01 , to create, save and make the script executable.

Script (user_var.sh) >

The script starts with the shebang line ( #!/bin/bash ) to specify that the Bash shell should be used for executing the script. The read command is then used twice, each with the -p option, to prompt the user for input. Both the name and age variables take the name and age of the user and store them in the name and age variable with the help of the read command . Then the script uses the echo command to print the values of the variable’s name and age , respectively. The $ name and $age syntax are used to access the values stored in the variables and display them in the output.

Now, run the following command into your terminal to execute the bash file.

Input from User and Variable Assignment

Case 03: Variable Assignment Using Positional Parameters

In Bash , you can assign values to variables using positional parameters . Positional parameters are special variables that hold arguments passed to the script when it is executed. They are referenced by their position, starting from $0 for the script name, $1 for the first argument , $2 for the second argument , and so on. To do the same use the below script.

Script (var_command_line.sh) >

The script starts with the shebang line ( #!/bin/bash ) to specify that the Bash shell should be used for executing the script. The script uses the special variables $1 and $2, which represent the first and second command – line arguments , respectively, and assigns their values to the name and age variables . The $ name and $age syntax are used to access the values stored in the variables and display them using the echo command .

Now, run the following command into your terminal to execute the script.

Variable Assignment Using Positional Parameters

Upon execution of the Bash file , the script takes two command-line arguments, John and 30 , and returns the output Name : John and Age : 30 in the command line.

Case 04:  Environment Variables and Variable Scope

In Bash script , Environment Variables are another type of variable. Those variables are available in the current session and its child processes once you export your own variable in the environment. However, you can access those and scope it to a function. Here’s a sample Bash script code of environment variables and variable scope describing the concept.

Script (var_scope.sh) >

The script starts with the shebang line ( #!/bin/bash ) to specify that the Bash shell should be used for executing the script. Then, an environment variable named MY_VARIABLE is assigned the value “ Hello, World! ” using the export command . The script also defines a Bash function called my_function . Inside this function, a local variable named local_var is declared using the local keyword . After defining the function, the script proceeds to print the value of the environment variable MY_VARIABLE , which is accessible throughout the script. Upon calling the my_function , it prints the value of the local variable local_var , demonstrating its local scope .

Finally, run the following command into your terminal to execute the bash file.

Environment Variables and Variable Scope

Upon printing the My_VARIABLE and calling the my_function, the code returns “ Environment Variable: Hello, World ” and “ I am a local variable ” respectively.

In conclusion, variable declaration and assignment is a very straightforward process and does not take any extra effort to declare the variable first, just like the Python programming language . In this article, I have tried to give you a guideline on how to declare and assign variables in a Bash Scripts . I have also provided some practical cases related to this topic. However, if you have any questions or queries regarding this article, feel free to comment below. I will get back to you soon. Thank You!

People Also Ask

Related Articles

  • How to Declare Variable in Bash Scripts? [5 Practical Cases]
  • Bash Variable Naming Conventions in Shell Script [6 Rules]
  • How to Assign Variables in Bash Script? [8 Practical Cases]
  • How to Check Variable Value Using Bash Scripts? [5 Cases]
  • How to Use Default Value in Bash Scripts? [2 Methods]
  • How to Use Set – $Variable in Bash Scripts? [2 Examples]
  • How to Read Environment Variables in Bash Script? [2 Methods]
  • How to Export Environment Variables with Bash? [4 Examples]

<< Go Back to Bash Variables | Bash Scripting Tutorial

Mohammad Shah Miran

Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

linuxsimply white logo

Get In Touch!

card

Legal Corner

dmca

Copyright © 2024 LinuxSimply | All Rights Reserved.

How to Assign One Variable to Another in Bash

  • Linux Howtos
  • How to Assign One Variable to Another in …

Declare a Variable in Bash

Assign one variable to another in bash.

How to Assign One Variable to Another in Bash

In Bash, a variable is created by giving its reference a value. Although the built-in declare statement in Bash is not required to declare a variable directly, it is frequently used for more advanced variable management activities.

To define a variable, all you have to do is give it a name and a value. Your variables should have descriptive names that remind you of their relevance. A variable name cannot contain spaces or begin with a number.

However, it can begin with an underscore. Apart from that, any combination of uppercase and lowercase alphanumeric characters is permitted.

To create a variable in the Bash shell, you must assign a value to that variable.

Here, varname is the name of the newly created variable, and value is the value assigned to the variable. A value can be null.

Let’s look at an example.

Using the echo command, we can see the value of a variable. Whenever you refer to the value of a variable, you must prefix it with the dollar symbol $ , as seen below.

Let’s put all of our variables to work at the same time.

We can run dest=$source to assign one variable to another. The dest denotes the destination variable, and $source denotes the source variable.

Let’s assign variable a to variable b .

Hence, we can easily assign the value of one variable to another using the syntax above.

Related Article - Bash Variable

  • How to Multiply Variables in Bash
  • How to Execute Commands in a Variable in Bash Script
  • How to Increment Variable Value by One in Shell Programming
  • Bash Variable Scope
  • How to Modify a Global Variable Within a Function in Bash
  • Variable Interpolation in Bash Script

We Love Servers.

  • WHY IOFLOOD?
  • BARE METAL CLOUD
  • DEDICATED SERVERS

How to Set Variables in Bash: Shell Script Syntax Guide

Bash script setting a variable depicted with assignment symbols and variable name icons highlighting equal signs and data assignment markers

Do you find setting variables in Bash a bit tricky? You’re not alone. Many developers find Bash variable assignment a bit puzzling, but we’re here to help! You can think of Bash variables as small storage boxes – they allow us to store data temporarily for later use, providing a versatile and handy tool for various tasks.

In this guide, we’ll walk you through the process of setting variables in Bash , from the basics to more advanced techniques. We’ll cover everything from simple variable assignment, manipulating and using variables, to more complex uses such as setting environment variables or using special variable types.

So, let’s dive in and start mastering Bash variables!

TL;DR: How Do I Set a Variable in Bash?

To set a variable in Bash, you use the '=' operator with the syntax, VAR=Value . There must be no spaces between the variable name, the '=' operator, and the value you want to assign to the variable.

Here’s a simple example:

In this example, we’ve set a variable named VAR to the string ‘Hello, World!’. We then use the echo command to print the value of VAR , resulting in ‘Hello, World!’ being printed to the console.

This is just the basics of setting variables in Bash. There’s much more to learn about using variables effectively in your scripts. Continue reading for more detailed information and advanced usage scenarios.

Table of Contents

Bash Variable Basics: Setting and Using Variables

Advanced bash variable usage, alternative approaches to bash variables, troubleshooting bash variables: common pitfalls and solutions, understanding variables in programming and bash, expanding bash variable usage in larger projects, wrapping up: mastering bash variables.

In Bash, setting a variable is a straightforward process. It’s done using the ‘=’ operator with no spaces between the variable name, the ‘=’ operator, and the value you want to assign to the variable. Let’s dive into a basic example:

In this example, we’ve created a variable named myVar and assigned it the value ‘Bash Beginner’. The echo command is then used to print the value of myVar , which results in ‘Bash Beginner’ being printed to the console.

The advantages of using variables in Bash are numerous. They allow you to store and manipulate data, making your scripts more flexible and efficient. However, there are potential pitfalls to be aware of. One common mistake is adding spaces around the ‘=’ operator when assigning values to variables. In Bash, this will result in an error.

Here’s what happens when you add spaces around the ‘=’ operator:

As you can see, Bash interprets myVar as a command, which is not what we intended. So, remember, no spaces around the ‘=’ operator when setting variables in Bash!

As you progress in Bash scripting, you’ll encounter instances where you need to use more advanced techniques for setting variables. One such technique is setting environment variables, which are variables that are available system-wide and to other programs. Another is using special variable types, such as arrays.

Setting Environment Variables

Environment variables are an essential part of Bash scripting. They allow you to set values that are going to be used by other programs or processes. To create an environment variable, you can use the export command:

In this example, we’ve created an environment variable called GREETING with the value ‘Hello, World!’. The export command makes GREETING available to child processes.

Using Array Variables

Bash also supports array variables. An array is a variable that can hold multiple values. Here’s how you can create an array variable:

In this case, we’ve created an array myArray containing three elements. We then print the second element (arrays in Bash are zero-indexed, so index 1 corresponds to the second element) using the echo command.

These are just a couple of examples of the more advanced ways you can use variables in Bash. As you continue to learn and experiment, you’ll find that variables are a powerful tool in your Bash scripting arsenal.

While setting variables in Bash is typically straightforward, there are alternative approaches and techniques that can offer more flexibility or functionality in certain scenarios. These can include using command substitution, arithmetic expansion, or parameter expansion.

Command Substitution

Command substitution allows you to assign the output of a command to a variable. This can be particularly useful for dynamic assignments. Here’s an example:

In this example, we’ve used command substitution ( $(command) ) to assign the current date to the myDate variable.

Arithmetic Expansion

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. For instance:

Here, we’ve used arithmetic expansion ( $((expression)) ) to add 5 and 5 and assign the result to the num variable.

Parameter Expansion

Parameter expansion provides advanced operations and manipulations on variables. This can include string replacement, substring extraction, and more. Here’s an example of string replacement:

In this case, we’ve used parameter expansion ( ${variable/search/replace} ) to replace ‘World’ with ‘Reader’ in the greeting variable.

These alternative approaches provide advanced ways of working with variables in Bash. They can offer more functionality and flexibility, but they also come with their own considerations. For instance, they can make scripts more complex and harder to read if not used judiciously. As always, the best approach depends on the specific task at hand.

While working with Bash variables, you might encounter some common errors or obstacles. Understanding these can help you write more robust and effective scripts.

Unassigned Variables

One common mistake is trying to use a variable that hasn’t been assigned a value. This can lead to unexpected behavior or errors. For instance:

In this case, because unassignedVar hasn’t been assigned a value, nothing is printed to the console.

Spaces Around the ‘=’ Operator

As mentioned earlier, adding spaces around the ‘=’ operator when assigning values to variables will result in an error:

Bash interprets myVar as a command, which is not what we intended. So, remember, no spaces around the ‘=’ operator when setting variables in Bash!

Variable Name Considerations

Variable names in Bash are case-sensitive, and can include alphanumeric characters and underscores. However, they cannot start with a number. Trying to create a variable starting with a number results in an error:

In this case, Bash doesn’t recognize 1var as a valid variable name and throws an error.

Best Practices and Optimization

When working with Bash variables, it’s good practice to use descriptive variable names. This makes your scripts easier to read and understand. Also, remember to unset variables that are no longer needed, especially in large scripts. This can help to optimize memory usage.

Understanding these common pitfalls and best practices can help you avoid errors and write better Bash scripts.

Variables are a fundamental concept in programming. In simple terms, a variable can be seen as a container that holds a value. This value can be a number, a string, a file path, an array, or even the output of a command.

In Bash, variables are used to store and manipulate data. The data stored in a variable can be accessed by referencing the variable’s name, preceded by a dollar sign ($).

Here is an example:

In this example, we have a variable named website that holds the value ‘www.google.com’. The echo command is used to print the value of the website variable, resulting in ‘www.google.com’ being output to the console.

Variables in Bash can be assigned any type of value, and the type of the variable is dynamically determined by the value it holds. This is different from some other languages, where the variable type has to be declared upon creation.

In addition to user-defined variables, Bash also provides a range of built-in variables, such as $HOME , $PATH , and $USER , which hold useful information and can be used in your scripts.

Understanding how variables work in Bash, and in programming in general, is crucial for writing effective scripts and automating tasks.

Setting variables in Bash is not just limited to small scripts. They play a crucial role in larger scripts or projects, helping to store and manage data effectively. The use of variables can streamline your code, making it more readable and maintainable.

Leveraging Variables in Scripting

In larger scripts, variables can be used to store user input, configuration settings, or the results of commands that need to be used multiple times. This can help to make your scripts more dynamic and efficient.

Accompanying Commands and Functions

When setting variables in Bash, you might often find yourself using certain commands or functions. These can include echo for printing variable values, read for getting user input into a variable, or unset for deleting a variable. Understanding these accompanying commands and functions can help you get the most out of using variables in Bash.

In this example, the read command is used to get user input and store it in the name variable. The echo command then uses this variable to greet the user.

Further Resources for Bash Variable Mastery

To deepen your understanding of Bash variables and their usage, you might find the following resources helpful:

  • GNU Bash Manual : This is the official manual for Bash, and it provides a comprehensive overview of all its features, including variables.

Bash Scripting Guide : This is a detailed guide to Bash scripting, with plenty of examples and explanations.

Bash Variables : This tutorial offers a detailed look at Bash variables, including their declaration, assignment, and usage.

These resources offer in-depth information about Bash variables and related topics, and can provide valuable insights as you continue your Bash scripting journey.

In this comprehensive guide, we’ve delved deep into the world of Bash variables. From simple variable assignment to more complex uses such as setting environment variables or using special variable types, we’ve covered it all.

We began with the basics, showing you how to set and use variables in Bash. We then explored more advanced techniques, such as setting environment variables and using array variables. Along the way, we also discussed alternative approaches, including command substitution, arithmetic expansion, and parameter expansion.

We also tackled common pitfalls and provided solutions to help you avoid these errors. Additionally, we compared the different methods of setting variables and their benefits, giving you a broader understanding of Bash variables.

MethodProsCons
Simple Variable AssignmentSimple and straightforwardLimited to single values
Environment VariablesAvailable system-wideCould affect other processes
Array VariablesCan hold multiple valuesMore complex to use
Command SubstitutionDynamic assignmentsDepends on command output
Arithmetic ExpansionAllows arithmetic operationsLimited to numeric values
Parameter ExpansionAdvanced string operationsCan make scripts complex

Whether you’re just getting started with Bash scripting or you’re looking to advance your skills, we hope this guide has given you a deeper understanding of Bash variables and how to use them effectively.

Mastering Bash variables is a key step in becoming proficient in Bash scripting. With the knowledge and techniques you’ve gained from this guide, you’re now well-equipped to use variables effectively in your scripts. Happy scripting!

About Author

Gabriel Ramuglia

Gabriel Ramuglia

Gabriel is the owner and founder of IOFLOOD.com , an unmanaged dedicated server hosting company operating since 2010.Gabriel loves all things servers, bandwidth, and computer programming and enjoys sharing his experience on these topics with readers of the IOFLOOD blog.

Related Posts

Illustration of a Linux terminal displaying the installation of the killall command used for terminating processes by name

LinuxConfig

Bash Script: Set variable example

If you are writing a Bash script and have some information that may change during the execution of the script, or that normally changes during subsequent executions, then this should be set as a variable. Setting a variable in a Bash script allows you to recall that information later in the script, or change it as needed. In the case of integers, you can increment or decrement variables, which is useful for counting loops and other scenarios.

In this tutorial, you will learn how to set variables and use them in a Bash script on a Linux system . Check some of the examples below to see how variables works.

In this tutorial you will learn:

  • How to set a variable in a Bash script
  • How to use a previously set variable
  • How to use a variable inside of another variable

How to set a variable in a Bash script

Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any
Software Bash shell (installed by default)
Other Privileged access to your Linux system as root or via the command.
Conventions – requires given to be executed with root privileges either directly as a root user or by use of command
– requires given to be executed as a regular non-privileged user

How to set variable in Bash script

First, let’s go over how setting a variable is done in a Bash script. This will familiarize you with the syntax so you can easily interpret the coming examples, and eventually write your own from scratch.

Executing the script gives us this output:

This is the probably the most basic example of a variable as possible, but it gets the point across. Let’s go over what is happening here:

  • The name of the variable in this example is simply var .
  • The variable is declared by using an equal sign = .
  • The variable is set to "Hello World" . The quotes are necessary in this case because of the space.
  • In order to call the variable later in the script, we precede it with a dollar sign $ .

Next, look at the examples below to see more practical examples of setting a variable in a Bash script.

Bash Script: Set variable examples

Check out the examples below to see how to set variables within a Bash script.

Here is the result from executing the script:

The lesson to take away from this example is that you can re-use a variable inside of a Bash script.

The lesson to take away from this example is that variables are very useful when reading data from the user, whether they specify that data as flags or as a response to a prompt. There is another lesson here too. Notice that when declaring the $number variable, we use the $directory variable as well. In other words, a variable inside of a variable.

Closing Thoughts

In this tutorial, you learned how to set variables and use them in Bash scripting on a Linux system. As you can see from the examples, using variables is incredibly useful and will be a common staple in most Bash scripts. The examples shown here are basic in order to introduce you to the concept, but it is normal for a Bash script to contain many variables.

Related Linux Tutorials:

  • Mastering Bash Script Loops
  • Nested Loops in Bash Scripts
  • Bash Scripting: Mastering Arithmetic Operations
  • An Introduction to Linux Automation, Tools and Techniques
  • Mastering String Concatenation in Bash Scripting
  • Customizing and Utilizing History in the Shell
  • String Concatenation in Bash Loops
  • Ansible loops examples and introduction
  • Things to do after installing Ubuntu 22.04 Jammy…
  • Bash Scripting: Operators

Linux Forum

Linux Bash: Multiple Variable Assignment

Last updated: March 18, 2024

assignment variable bash

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

1. Overview

Assigning multiple variables in a single line of code is a handy feature in some programming languages, such as Python and PHP.

In this quick tutorial, we’ll take a closer look at how to do multiple variable assignment in Bash scripts.

2. Multiple Variable Assignment

Multiple variable assignment is also known as tuple unpacking or iterable unpacking.

It allows us to assign multiple variables at the same time in one single line of code.

Let’s take a look at a simple Python example to understand what multiple variable assignment looks like:

In the example above, we assigned three string values to three variables in one shot.

Next, let’s prove if the values are assigned to variables correctly using the  print() function:

As the output shows, the assignment works as we expect.

Using the multiple variable assignment technique in Bash scripts can make our code look compact and give us the benefit of better performance, particularly when we want to assign multiple variables by the output of expensive command execution.

For example, let’s say we want to assign seven variables – the calendar week number, year, month, day, hour, minute, and second – based on the current date. We can straightforwardly do:

These assignments work well.

However, during the seven executions of the date commands, the current time is always changing, and we could get unexpected results.

Further, we’ll execute the date command seven times. If the command were an expensive process, the multiple assignments would definitely hurt the performance.

We can tweak the output format to ask the date command to output those required fields in one single shot:

In other words, if we can somehow use the multiple variable assignment technique, we merely need to execute the date command once to assign the seven variables, something like:

Unfortunately, not all programming languages support the multiple variable assignment feature. Bash and shell script don’t support this feature.  Therefore, the assignment above won’t work.

However, we can achieve our goal in some other ways.

Next, let’s figure them out.

3. Using the read Command

The read command is a powerful Bash built-in utility to read standard input (stdin) to shell variables.

It allows us to assign multiple variables at once:

We use the -r option in the example above to disable backslash escapes when it reads the values.

However, the read command reads from stdin. It’s not so convenient to be used as variable assignments in shell scripts. After all, not all variables are assigned by user inputs.

But there are some ways to redirect values to stdin. Next, let’s see how to do it.

3.1. Using Process Substitution and IO Redirection

We know that we can use “ < FILE ” to redirect FILE  to stdin. Further, process substitution can help us to make the output of a command appear like a file.

Therefore, we can combine the process substitution and the IO redirection together to feed the  read command :

Let’s test it with the previous date command and seven variables’ assignment problem:

As the output above shows, we’ve assigned seven variables in one shot using the process substitution and IO redirection trick.

3.2. Using Command Substitution and the Here-String

Alternatively, we can use the here-string to feed the stdin of the read command:

If we replace the hard-coded string with a command substitution , we can set multiple variables using a command’s output.

Let’s test with the seven variables and the date command scenario:

We’ve assigned seven variables in one shot. Also, the date command is executed only once.

Thus, the read command can help us to achieve multiple variables assignment.

3.3. Changing the Delimiter

The  read command will take the value of the IFS   variable as the delimiter.  By default, it’s whitespace.

But we know that the output of a command is not always delimited by whitespace.

Let’s change the output format of the date command:

This time, the output is delimited by the ‘@’ character and has three fields: the week number, the current date and time, and the weekday of the current date. The second field contains a space.

Now, we’re about to assign the three fields to three variables in one shot.

Obviously, it won’t work with the default delimiter. We can change the delimiter by setting the IFS  variable:

It’s worthwhile to mention that in the example above, the change to the IFS variable only affects the  read command following it.

4. Using an Array

Another way to assign multiple variables using a command’s output is to assign the command output fields to an array.

Let’s show how it works with the date command and seven variables example:

In the example, we used the Bash built-in  readarray command to read the date command’s output.

The default delimiter used by the readarray command is a newline character . But we can set space as the delimiter using the -d option.

5. Conclusion

In this article, we’ve learned what the multiple variable assignment technique is.

Further, we’ve addressed how to achieve multiple variable assignment in Bash scripts through examples, even though Bash doesn’t support this language feature.

Bash Variables Explained: A Simple Guide With Examples

4

Your changes have been saved

Email is sent

Email has already been sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

This Note-Taking System Finally Made Schoolwork Easier for Me

I customized my mac's dock using these hidden commands: here's how, this windows tool can let in viruses without detection.

Variables are used for storing values of different types during program execution. There are two types of variables in Bash scripting: global and local.

Global variables can be used by all Bash scripts on your system, while local variables can only be used within the script (or shell) in which they're defined.

Global variables are generally provided on the system by default and are mainly environment and configuration variables. Local variables, on the other hand, are user-defined and have arbitrary uses.

Bash Local Variables

To create a variable, you need to assign a value to your variable name. Bash is an untyped language, so you don't have to indicate a data type when defining your variables.

Bash also allows multiple assignments on a single line:

Just like many other programming languages, Bash uses the assignment operator = to assign values to variables. It's important to note that there shouldn't be any spaces on either side of the assignment operator. Otherwise, you'll get a compilation error.

Related: What Does "Bash" Mean in Linux?

Another key point to note: Bash doesn't allow you to define a variable first and then assign a value to it later. You must assign a value to the variable at creation.

Sometimes, you may need to assign a string that has a space in it to your variable. In such a case, enclose the string in quotes.

Notice the use of single quotes. These quotes are also called "strong quotes" because they assign the value precisely as it's written without regard to any special characters.

In the example above, you could have also used double quotes ("weak quotes"), though this doesn't mean they can always be used interchangeably. This is because double quotes will substitute special characters (such as those with $ ), instead of interpreting them literally.

See the example below:

If you want to assign a command-line output to your variable, use backquotes ( `` ). They'll treat the string enclosed in them as a terminal command and return its result.

Parameter Expansion in Bash

Parameter Expansion simply refers to accessing the value of a variable. In its simplest form, it uses the special character $ followed by the variable name (with no spaces in between):

You can also use the syntax ${variableName} to access a variable's value. This form is more suitable when confusion surrounding the variable name may arise.

If you leave out the curly brackets, ${m}ical will be interpreted as a compound variable (that doesn't exist). This use of curly brackets with variables is known as "substitution".

Global Variables

As mentioned earlier, your Linux system has some built-in variables that can be accessed across all of your scripts (or shells). These variables are accessed using the same syntax as local variables.

Related: How to Create and Execute Bash Scripts in Linux

Most of these variables are in BLOCK letters. However, some are single characters that aren't even alphanumeric characters.

Here are some common useful global variables:

HOME : Provides the user's home directory

SHELL : Provides the type of shell you're using (e.g Bash, csh..etc)

? : Provides the exit status of the previous command

To get a list of global variables on your system, run the printenv (or env) command:

Loops in Bash Scripting

Now you know what variables are, how to assign them, and how to perform basic Bash logic using them.

Loops enable you to iterate through multiple statements. Bash accommodates for loops and while loops with a simple syntax for all of your looping needs.

If you're mastering the art of Bash development, for loops ought to be next up on your list.

  • Programming
  • Linux Bash Shell
  • Coding Tips

Previous: Bourne Shell Variables , Up: Shell Variables   [ Contents ][ Index ]

5.2 Bash Variables

These variables are set or used by Bash, but other shells do not normally treat them specially.

A few variables used by Bash are described in different chapters: variables for controlling the job control facilities (see Job Control Variables ).

($_, an underscore.) At shell startup, set to the pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous simple command executed in the foreground, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file.

The full pathname used to execute the current instance of Bash.

A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -s option to the shopt builtin command (see The Shopt Builtin ). The options appearing in BASHOPTS are those reported as ‘ on ’ by ‘ shopt ’. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.

Expands to the process ID of the current Bash process. This differs from $$ under certain circumstances, such as subshells that do not require Bash to be re-initialized. Assignments to BASHPID have no effect. If BASHPID is unset, it loses its special properties, even if it is subsequently reset.

An associative array variable whose members correspond to the internal list of aliases as maintained by the alias builtin. (see Bourne Shell Builtins ). Elements added to this array appear in the alias list; however, unsetting array elements currently does not cause aliases to be removed from the alias list. If BASH_ALIASES is unset, it loses its special properties, even if it is subsequently reset.

An array variable whose values are the number of parameters in each frame of the current bash execution call stack. The number of parameters to the current subroutine (shell function or script executed with . or source ) is at the top of the stack. When a subroutine is executed, the number of parameters passed is pushed onto BASH_ARGC . The shell sets BASH_ARGC only when in extended debugging mode (see The Shopt Builtin for a description of the extdebug option to the shopt builtin). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values.

An array variable containing all of the parameters in the current bash execution call stack. The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto BASH_ARGV . The shell sets BASH_ARGV only when in extended debugging mode (see The Shopt Builtin for a description of the extdebug option to the shopt builtin). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values.

When referenced, this variable expands to the name of the shell or shell script (identical to $0 ; See Special Parameters , for the description of special parameter 0). Assignment to BASH_ARGV0 causes the value assigned to also be assigned to $0 . If BASH_ARGV0 is unset, it loses its special properties, even if it is subsequently reset.

An associative array variable whose members correspond to the internal hash table of commands as maintained by the hash builtin (see Bourne Shell Builtins ). Elements added to this array appear in the hash table; however, unsetting array elements currently does not cause command names to be removed from the hash table. If BASH_CMDS is unset, it loses its special properties, even if it is subsequently reset.

The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap. If BASH_COMMAND is unset, it loses its special properties, even if it is subsequently reset.

The value is used to set the shell’s compatibility level. See Shell Compatibility Mode , for a description of the various compatibility levels and their effects. The value may be a decimal number (e.g., 4.2) or an integer (e.g., 42) corresponding to the desired compatibility level. If BASH_COMPAT is unset or set to the empty string, the compatibility level is set to the default for the current version. If BASH_COMPAT is set to a value that is not one of the valid compatibility levels, the shell prints an error message and sets the compatibility level to the default for the current version. The valid values correspond to the compatibility levels described below (see Shell Compatibility Mode ). For example, 4.2 and 42 are valid values that correspond to the compat42 shopt option and set the compatibility level to 42. The current version is also a valid value.

If this variable is set when Bash is invoked to execute a shell script, its value is expanded and used as the name of a startup file to read before executing the script. See Bash Startup Files .

The command argument to the -c invocation option.

An array variable whose members are the line numbers in source files where each corresponding member of FUNCNAME was invoked. ${BASH_LINENO[$i]} is the line number in the source file ( ${BASH_SOURCE[$i+1]} ) where ${FUNCNAME[$i]} was called (or ${BASH_LINENO[$i-1]} if referenced within another shell function). Use LINENO to obtain the current line number.

A colon-separated list of directories in which the shell looks for dynamically loadable builtins specified by the enable command.

An array variable whose members are assigned by the ‘ =~ ’ binary operator to the [[ conditional command (see Conditional Constructs ). The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the n th parenthesized subexpression.

An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}

Incremented by one within each subshell or subshell environment when the shell begins executing in that environment. The initial value is 0. If BASH_SUBSHELL is unset, it loses its special properties, even if it is subsequently reset.

A readonly array variable (see Arrays ) whose members hold version information for this instance of Bash. The values assigned to the array members are as follows:

The major version number (the release ).

The minor version number (the version ).

The patch level.

The build version.

The release status (e.g., beta1 ).

The value of MACHTYPE .

The version number of the current instance of Bash.

If set to an integer corresponding to a valid file descriptor, Bash will write the trace output generated when ‘ set -x ’ is enabled to that file descriptor. This allows tracing output to be separated from diagnostic and error messages. The file descriptor is closed when BASH_XTRACEFD is unset or assigned a new value. Unsetting BASH_XTRACEFD or assigning it the empty string causes the trace output to be sent to the standard error. Note that setting BASH_XTRACEFD to 2 (the standard error file descriptor) and then unsetting it will result in the standard error being closed.

Set the number of exited child status values for the shell to remember. Bash will not allow this value to be decreased below a POSIX -mandated minimum, and there is a maximum value (currently 8192) that this may not exceed. The minimum value is system-dependent.

Used by the select command to determine the terminal width when printing selection lists. Automatically set if the checkwinsize option is enabled (see The Shopt Builtin ), or in an interactive shell upon receipt of a SIGWINCH .

An index into ${COMP_WORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion ).

The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the current command, the value of this variable is equal to ${#COMP_LINE} . This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

Set to an integer value corresponding to the type of completion attempted that caused a completion function to be called: TAB , for normal completion, ‘ ? ’, for listing completions after successive tabs, ‘ ! ’, for listing alternatives on partial word completion, ‘ @ ’, to list completions if the word is not unmodified, or ‘ % ’, for menu completion. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

The key (or final key of a key sequence) used to invoke the current completion function.

The set of characters that the Readline library treats as word separators when performing word completion. If COMP_WORDBREAKS is unset, it loses its special properties, even if it is subsequently reset.

An array variable consisting of the individual words in the current command line. The line is split into words as Readline would split it, using COMP_WORDBREAKS as described above. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion ).

An array variable from which Bash reads the possible completions generated by a shell function invoked by the programmable completion facility (see Programmable Completion ). Each array element contains one possible completion.

An array variable created to hold the file descriptors for output from and input to an unnamed coprocess (see Coprocesses ).

An array variable containing the current contents of the directory stack. Directories appear in the stack in the order they are displayed by the dirs builtin. Assigning to members of this array variable may be used to modify directories already in the stack, but the pushd and popd builtins must be used to add and remove directories. Assignment to this variable will not change the current directory. If DIRSTACK is unset, it loses its special properties, even if it is subsequently reset.

If Bash finds this variable in the environment when the shell starts with value ‘ t ’, it assumes that the shell is running in an Emacs shell buffer and disables line editing.

Expanded and executed similarly to BASH_ENV (see Bash Startup Files ) when an interactive shell is invoked in POSIX Mode (see Bash POSIX Mode ).

Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch as a floating point value with micro-second granularity (see the documentation for the C library function time for the definition of Epoch). Assignments to EPOCHREALTIME are ignored. If EPOCHREALTIME is unset, it loses its special properties, even if it is subsequently reset.

Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch (see the documentation for the C library function time for the definition of Epoch). Assignments to EPOCHSECONDS are ignored. If EPOCHSECONDS is unset, it loses its special properties, even if it is subsequently reset.

The numeric effective user id of the current user. This variable is readonly.

A colon-separated list of shell patterns (see Pattern Matching ) defining the list of filenames to be ignored by command search using PATH . Files whose full pathnames match one of these patterns are not considered executable files for the purposes of completion and command execution via PATH lookup. This does not affect the behavior of the [ , test , and [[ commands. Full pathnames in the command hash table are not subject to EXECIGNORE . Use this variable to ignore shared library files that have the executable bit set, but are not executable files. The pattern matching honors the setting of the extglob shell option.

The editor used as a default by the -e option to the fc builtin command.

A colon-separated list of suffixes to ignore when performing filename completion. A filename whose suffix matches one of the entries in FIGNORE is excluded from the list of matched filenames. A sample value is ‘ .o:~ ’

An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is "main" . This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset.

This variable can be used with BASH_LINENO and BASH_SOURCE . Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]} . The caller builtin displays the current call stack using this information.

If set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed this nesting level will cause the current command to abort.

A colon-separated list of patterns defining the set of file names to be ignored by filename expansion. If a file name matched by a filename expansion pattern also matches one of the patterns in GLOBIGNORE , it is removed from the list of matches. The pattern matching honors the setting of the extglob shell option.

An array variable containing the list of groups of which the current user is a member. Assignments to GROUPS have no effect. If GROUPS is unset, it loses its special properties, even if it is subsequently reset.

Up to three characters which control history expansion, quick substitution, and tokenization (see History Expansion ). The first character is the history expansion character, that is, the character which signifies the start of a history expansion, normally ‘ ! ’. The second character is the character which signifies ‘quick substitution’ when seen as the first character on a line, normally ‘ ^ ’. The optional third character is the character which indicates that the remainder of the line is a comment when found as the first character of a word, usually ‘ # ’. The history comment character causes history substitution to be skipped for the remaining words on the line. It does not necessarily cause the shell parser to treat the rest of the line as a comment.

The history number, or index in the history list, of the current command. Assignments to HISTCMD are ignored. If HISTCMD is unset, it loses its special properties, even if it is subsequently reset.

A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ‘ ignorespace ’, lines which begin with a space character are not saved in the history list. A value of ‘ ignoredups ’ causes lines which match the previous history entry to not be saved. A value of ‘ ignoreboth ’ is shorthand for ‘ ignorespace ’ and ‘ ignoredups ’. A value of ‘ erasedups ’ causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE . The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL .

The name of the file to which the command history is saved. The default value is ~/.bash_history .

The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines by removing the oldest entries. The history file is also truncated to this size after writing it when a shell exits. If the value is 0, the history file is truncated to zero size. Non-numeric values and numeric values less than zero inhibit truncation. The shell sets the default value to the value of HISTSIZE after reading any startup files.

A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must match the complete line (no implicit ‘ * ’ is appended). Each pattern is tested against the line after the checks specified by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, ‘ & ’ matches the previous history line. ‘ & ’ may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE . The pattern matching honors the setting of the extglob shell option.

HISTIGNORE subsumes the function of HISTCONTROL . A pattern of ‘ & ’ is identical to ignoredups , and a pattern of ‘ [ ]* ’ is identical to ignorespace . Combining these two patterns, separating them with a colon, provides the functionality of ignoreboth .

The maximum number of commands to remember on the history list. If the value is 0, commands are not saved in the history list. Numeric values less than zero result in every command being saved on the history list (there is no limit). The shell sets the default value to 500 after reading any startup files.

If this variable is set and not null, its value is used as a format string for strftime to print the time stamp associated with each history entry displayed by the history builtin. If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines.

Contains the name of a file in the same format as /etc/hosts that should be read when the shell needs to complete a hostname. The list of possible hostname completions may be changed while the shell is running; the next time hostname completion is attempted after the value is changed, Bash adds the contents of the new file to the existing list. If HOSTFILE is set, but has no value, or does not name a readable file, Bash attempts to read /etc/hosts to obtain the list of possible hostname completions. When HOSTFILE is unset, the hostname list is cleared.

The name of the current host.

A string describing the machine Bash is running on.

Controls the action of the shell on receipt of an EOF character as the sole input. If set, the value denotes the number of consecutive EOF characters that can be read as the first character on an input line before the shell will exit. If the variable exists but does not have a numeric value, or has no value, then the default is 10. If the variable does not exist, then EOF signifies the end of input to the shell. This is only in effect for interactive shells.

The name of the Readline initialization file, overriding the default of ~/.inputrc .

If Bash finds this variable in the environment when the shell starts, it assumes that the shell is running in an Emacs shell buffer and may disable line editing depending on the value of TERM .

Used to determine the locale category for any category not specifically selected with a variable starting with LC_ .

This variable overrides the value of LANG and any other LC_ variable specifying a locale category.

This variable determines the collation order used when sorting the results of filename expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within filename expansion and pattern matching (see Filename Expansion ).

This variable determines the interpretation of characters and the behavior of character classes within filename expansion and pattern matching (see Filename Expansion ).

This variable determines the locale used to translate double-quoted strings preceded by a ‘ $ ’ (see Locale-Specific Translation ).

This variable determines the locale category used for number formatting.

This variable determines the locale category used for data and time formatting.

The line number in the script or shell function currently executing. If LINENO is unset, it loses its special properties, even if it is subsequently reset.

Used by the select command to determine the column length for printing selection lists. Automatically set if the checkwinsize option is enabled (see The Shopt Builtin ), or in an interactive shell upon receipt of a SIGWINCH .

A string that fully describes the system type on which Bash is executing, in the standard GNU cpu-company-system format.

How often (in seconds) that the shell should check for mail in the files specified in the MAILPATH or MAIL variables. The default is 60 seconds. When it is time to check for mail, the shell does so before displaying the primary prompt. If this variable is unset, or set to a value that is not a number greater than or equal to zero, the shell disables mail checking.

An array variable created to hold the text read by the mapfile builtin when no variable name is supplied.

The previous working directory as set by the cd builtin.

If set to the value 1, Bash displays error messages generated by the getopts builtin command.

A string describing the operating system Bash is running on.

An array variable (see Arrays ) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).

If this variable is in the environment when Bash starts, the shell enters POSIX mode (see Bash POSIX Mode ) before reading the startup files, as if the --posix invocation option had been supplied. If it is set while the shell is running, Bash enables POSIX mode, as if the command

had been executed. When the shell enters POSIX mode, it sets this variable if it was not already set.

The process ID of the shell’s parent process. This variable is readonly.

If this variable is set, and is an array, the value of each set element is interpreted as a command to execute before printing the primary prompt ( $PS1 ). If this is set but not an array variable, its value is used as a command to execute instead.

If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes (see Controlling the Prompt ). Characters removed are replaced with an ellipsis.

The value of this parameter is expanded like PS1 and displayed by interactive shells after reading a command and before the command is executed.

The value of this variable is used as the prompt for the select command. If this variable is not set, the select command prompts with ‘ #? ’

The value of this parameter is expanded like PS1 and the expanded value is the prompt printed before the command line is echoed when the -x option is set (see The Set Builtin ). The first character of the expanded value is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is ‘ + ’.

The current working directory as set by the cd builtin.

Each time this parameter is referenced, it expands to a random integer between 0 and 32767. Assigning a value to this variable seeds the random number generator. If RANDOM is unset, it loses its special properties, even if it is subsequently reset.

Any numeric argument given to a Readline command that was defined using ‘ bind -x ’ (see Bash Builtin Commands when it was invoked.

The contents of the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ).

The position of the mark (saved insertion point) in the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ). The characters between the insertion point and the mark are often called the region .

The position of the insertion point in the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ).

The default variable for the read builtin.

This variable expands to the number of seconds since the shell was started. Assignment to this variable resets the count to the value assigned, and the expanded value becomes the value assigned plus the number of seconds since the assignment. The number of seconds at shell invocation and the current time are always determined by querying the system clock. If SECONDS is unset, it loses its special properties, even if it is subsequently reset.

This environment variable expands to the full pathname to the shell. If it is not set when the shell starts, Bash assigns to it the full pathname of the current user’s login shell.

A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -o option to the set builtin command (see The Set Builtin ). The options appearing in SHELLOPTS are those reported as ‘ on ’ by ‘ set -o ’. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.

Incremented by one each time a new instance of Bash is started. This is intended to be a count of how deeply your Bash shells are nested.

This variable expands to a 32-bit pseudo-random number each time it is referenced. The random number generator is not linear on systems that support /dev/urandom or arc4random , so each returned number has no relationship to the numbers preceding it. The random number generator cannot be seeded, so assignments to this variable have no effect. If SRANDOM is unset, it loses its special properties, even if it is subsequently reset.

The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The ‘ % ’ character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.

A literal ‘ % ’.

The elapsed time in seconds.

The number of CPU seconds spent in user mode.

The number of CPU seconds spent in system mode.

The CPU percentage, computed as (%U + %S) / %R.

The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used.

The optional l specifies a longer format, including minutes, of the form MM m SS . FF s. The value of p determines whether or not the fraction is included.

If this variable is not set, Bash acts as if it had the value

If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed.

If set to a value greater than zero, TMOUT is treated as the default timeout for the read builtin (see Bash Builtin Commands ). The select command (see Conditional Constructs ) terminates if input does not arrive after TMOUT seconds when input is coming from a terminal.

In an interactive shell, the value is interpreted as the number of seconds to wait for a line of input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if a complete line of input does not arrive.

If set, Bash uses its value as the name of a directory in which Bash creates temporary files for the shell’s use.

The numeric real user id of the current user. This variable is readonly.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

How can I assign the output of a command to a shell variable?

I want to assign the result of an expression (i.e., the output from a command) to a variable and then manipulate it – for example, concatenate it with a string, then echo it.  Here's what I've got:

But that outputs:

So, it looks like that isn't getting assigned to $thefile , and is being printed as it's executed.

What am I missing?

  • shell-script
  • io-redirection

G-Man Says 'Reinstate Monica''s user avatar

  • Related: Getting the source directory of a Bash script from within –  kenorb Commented Jul 19, 2017 at 18:37

3 Answers 3

A shell assignment is a single word, with no space after the equal sign. So what you wrote assigns an empty value to thefile ; furthermore, since the assignment is grouped with a command, it makes thefile an environment variable and the assignment is local to that particular command, i.e. only the call to ls sees the assigned value.

You want to capture the output of a command, so you need to use command substitution :

(Some literature shows an alternate syntax thefile=`ls …` ; the backquote syntax is equivalent to the dollar-parentheses syntax except that quoting inside backquotes is weird sometimes, so just use $(…) .)

Other remarks about your script:

Combining -t (sort by time) with -U (don't sort with GNU ls ) doesn't make sense; just use -t .

Rather than using grep to match screenshots, it's clearer to pass a wildcard to ls and use head to capture the first file:

It's generally a bad idea to parse the output of ls . This could fail quite badly if you have file names with nonprintable characters. However, sorting files by date is difficult without ls , so it's an acceptable solution if you know you won't have unprintable characters or backslashes in file names.

Always use double quotes around variable substitutions , i.e. here write

Without double quotes, the value of the variable is reexpanded, which will cause trouble if it contains whitespace or other special characters.

You don't need semicolons at the end of a line. They're redundant but harmless.

In a shell script, it's often a good idea to include set -e . This tells the shell to exit if any command fails (by returning a nonzero status).

If you have GNU find and sort (in particular if you're running non-embedded Linux or Cygwin), there's another approach to finding the most recent file: have find list the files and their dates, and use sort and read (here assuming bash or zsh for -d '' to read a NUL-delimited record) to extract the youngest file.

If you're willing to write this script in zsh instead of bash, there's a much easier way to catch the newest file, because zsh has glob qualifiers that permit wildcard matches not only on names but also on file metadata. The (om[1]) part after the pattern is the glob qualifiers; om sorts matches by increasing age (i.e. by modification time, newest first) and [1] extracts the first match only. The whole match needs to be in parentheses because it's technically an array, since globbing returns a list of files, even if the [1] means that in this particular case the list contains (at most) one file.

Stéphane Chazelas's user avatar

  • 12 Wow! More info than I possibly could have hoped for. Thank you many times for your answer; I really appreciate all the effort you put into this! You've just shown me that I really, really have a lot to learn. I'm off to buy a book on bash :P. –  Nathan G. Commented Jul 4, 2011 at 0:10
  • 4 That's what I would call the definitive answer! :) –  alex Commented Jul 4, 2011 at 6:19

If you want to do it with multiline/multiple command/s then you can do this:

Jahid's user avatar

  • 2 This is a nice answer. is there a way that I can specify a variable as part of the command? for example output=$(echo $someVariable) –  Zach Smith Commented Apr 4, 2019 at 12:32

For completeness, in different shells:

Bourne shell

The Bourne shell from the late 70s was the shell that introduced command substitution. It's no longer in use nowadays but a number of shells have their syntax based on that of that shell.

Interprets the any shell code in a child process where the output is then going to a pipe. Meanwhile, the shell reads that output from the other end of the pipe and stores it in the $var variable.

Note however that all the trailing newline characters in that output are removed.

The Bourne shell had no array variable support, but you could store the words of the output of commands into the positional parameters ( $1 , $2 ...) with:

In earlier versions where -- was not supported.

The output of some code , beside the trailing newline stripping was also subject to $IFS -based splitting + globbing. For instance, if some code outputs foo,/*<newline><newline> and $IFS contains , , $1 will contain /foo and the remaining arguments are all the non-hidden files in / .

Also from the late 70s, early 80s, very popular at the time, still survives as tcsh on some systems despite its many shortcomings.

stores the words resulting of the splitting of the output of some code (on space, tab or newline) in the $array list variable.

Same except the splitting is done on newlines only (the elements of $array will be the non-empty lines of the output).

ksh88 and POSIX like shells.

These days, sh is one or other implementation of an interpreter for the standard sh language, which itself is mostly based on a subset of ksh88's, ksh88 being the last evolution of a shell written by David Korn, derived from the Bourne shell with some fixes and enhancements. Among those, there are bash, dash, ksh, yash, mksh, zsh (though for many of those, compliance to the sh specification has to be enabled via some option, or by calling them as sh ).

It works like the Bourne shell's var=`...` except it makes nesting them a lot easier, and doesn't mess up the interpretation of backslashes within.

Though ksh had arrays, array support was not included in the POSIX sh specification.

rc and derivatives

rc was the shell of Research Unix V10 in the late 80s and plan9, the once to be successor of Unix. There also exists a public domain clone of that shell which spawned a few derivatives: es and akanga at least. It's got a much better syntax than the ones above, but never really took off unfortunately.

Stores the output of any shell code , split on the characters of $ifs into the $array .

Same except that the specified chars are used instead of $ifs to do the splitting. With var = ``(){shell code} , the output is stored exactly with no splitting (the only shell that can actually do that out of the box).

ksh was the first Bourne-like shell to introduce arrays in the early 80s. Syntax was:

Like in the Bourne shell, it does trailing newline stripping, $IFS -splitting and globbing.

Can also be used to read the first line of the output of some command , split it on $IFS (but where backslash can be used to escape the separators and newline) and store the result in those variables.

It also works in zsh, but not in some other ksh-like shells such as bash, yash or pdksh/mksh where that read is run in a subshell (for sh , the standard leaves it unspecified whether than happens or not, so you can't use that portably in sh ). In bash, shopt -s lastpipe helps in non-interactive invocations of the shell.

Same except the words of that first line are stored in the array elements ( bash renamed the option to -a for its own read builtin).

ksh also introduced co-processes.

Could be used for instance to read the first and second line from the output of some command into respective variables.

zsh and bash also added co-process support later with different syntax.

zsh (another Bourne-like shell but also with features from csh and rc) introduced array support in version 2.0 in 1991 (a few months after its first version was released the previous year).

Would do newline stripping and IFS-splitting (not globbing) and assign the resulting words to the elements of the array.

That syntax was later copied by ksh93 in 1993 and bash 2.0 in 1996, though they do globbing on top like ksh88.

To split with things other than $IFS in zsh :

zsh is also the only shell that can store NUL characters in its variables, so the only shell that doesn't choke on the output of commands that contain such characters. NUL is actually in the default value of $IFS in zsh (in addition of space, tab and newline like in the other Bourne-like shells).

Can be used to store the output of some command up to the first NUL character into $var . Since NUL cannot occur in text, that's a way to store text as is. -d is from ksh93, but -d '' to delimit on NULs is a bash/zsh addition.

zsh also added some more options to read such as -k to read arbitrary numbers of characters (was initially meant to read key presses, but can be used for arbitrary characters when combined with -u to specify the fd to read from). ksh93 and later bash added -N / -n options with related semantics:

Stores the first 10 characters of the output of some command in $var .

A sysread building in the zsh/system module can also be used to read input in blocks as a raw'er interface to the read() system call.

A zpty builtin from the eponymous module can also be used to interact with a command via a pseudo-terminal pair, allowing you to send input and read its output in a more interactive fashion like expect does.

A complete rewrite of ksh by its author released in late 1993 and which has heavily inspired bash 2+ (and to some extent zsh and mksh)

That's the same as var=$(any shell code) except any shell code doesn't run in a subshell environment, which means it's slightly more efficient as the shell doesn't need to same and restore the environment after and means, modifications that you do inside persist afterwards.

It's also supported by recent versions of mksh .

stores the lines of some command (including their delimiter which you can remove with the -t option) in the elements of the $array array. <(...) called process substitution was added to ksh in the mid 80s, but couldn't be used as the target of a redirection initially (was addressed in ksh93 much later).

With bash 4.4+, you can use different delimiters than newline including NUL:

can be used for instance to store the contents of the NUL-delimited records in the output of find into the $array .

You can also do:

Which works even when the lastpipe option is not enabled (also works in zsh).

Though it looks like ksh's process subsitution, the feature there is called process redirection, and does not expand to the path of some named pipe, but assigns the corresponding fd (here 0) to the reading end of a pipe whose other end is connected to the output of the command.

A relative late comer with a significantly different syntax from other shells (often much better, though still of a moving target):

Assigns the contents of each line of the output of the shell code to elements of the array.

Would read the first line, split on $IFS (though will change) or arbitrary delimiters with -d delim and stores in $var1 , $var2 . read -a array for the words of that line to be stored in an array.

For the first two lines in different variables.

For everything up to the first NUL (so everything for text output) to be stored in $var .

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged bash shell-script io-redirection variable ..

  • The Overflow Blog
  • One of the best ways to get value for AI coding tools: generating tests
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...

Hot Network Questions

  • What properties of the fundamental group functor are needed to uniquely determine it upto natural isomorphism?
  • Offset+Length vs 2 Offsets
  • How did NASA figure out when and where the Apollo capsule would touch down on the ocean?
  • How can I switch from MAG to TRU heading in a 737?
  • How to increase distance by a unit after every instance in Geometric Nodes array?
  • Unwanted text replacement of two hyphens with an em-dash
  • Understanding symmetry in a double integral
  • Function with memories of its past life
  • O(nloglogn) Sorting Algorithm?
  • Tensor product of intersections in an abelian rigid monoidal category
  • For a bike with "Forged alloy crank with 44T compact disc chainring", can the chainring be removed?
  • Why do I often see bunches of medical helicopters hovering in clusters in various locations
  • Custom PCB with Esp32-S3 isn't recognised by Device Manager for every board ordered
  • Why was Panama Railroad in poor condition when US decided to build Panama Canal in 1904?
  • Why does counterattacking lead to a more drawish and less dynamic position than defending?
  • "There is a bra for every ket, but there is not a ket for every bra"
  • Longtable goes beyond the right margin and footnote does not fit under the table
  • Is it really a "space walk" (EVA proper) if you don't get your feet wet (in space)?
  • Is there an essential distinction between experienced and observed consciousness?
  • How to reply to a revise and resubmit review, saying is all good?
  • What's the difference between "Erase All Content and Settings" and using the Disk Utility to erase a Mac with Apple silicon
  • What is the oldest open math problem outside of number theory?
  • Drill perpendicular hole through thick lumber using handheld drill
  • Concerns with newly installed floor tile

assignment variable bash

Linux Haxor Logo

How to Assign Output of a Linux Command to a Variable in Bash

As a Linux system administrator or developer, it‘s common to need to assign the output of a command to a variable for later use in scripts or other contexts. Bash provides a simple way to capture the output of any Linux command and store it in a variable using command substitution.

In this comprehensive guide, we will cover the following topics related to assigning command output to a variable in Bash:

Why Assign Command Output to a Variable

Command substitution syntax, using $() for command substitution, using backticks “ for command substitution, comparison to piping, files, etc, performance considerations, assigning output of ls to a variable, assigning disk usage output to a variable, assigning current date to a variable, manipulating and processing output, guidelines and best practices, pitfalls to avoid.

So let‘s get started!

Here are some common reasons you may want to assign the output of a Linux command to a variable in Bash:

Reuse output in scripts – Store command output in a variable so you can easily refer to it multiple times without re-running the command. This helps improve performance by avoiding redundant executions.

Manipulate and format output – Assign output to a variable allows you to pipe and process it further before usage with tools like sed , awk , grep , etc.

Compare output values – Save previous output in a separate variable then compare to current output to check for changes.

Cleaner script syntax – Allows you to break up long commands but still access the output in a readable way.

Control script flow based on output – Check output values to make code decisions.

Portability – Wrap portable Linux commands instead of relying on external programs.

So while you can always directly reference command output using pipes, assignment allows much more flexible usage. Capturing output is a core Bash scripting concept.

The basic syntax for command substitution in Bash is:

Or alternatively, using backticks:

This runs the specified Linux command, captures the STDOUT output, and assigns it to the specified variable name for you to use later.

The command can be any valid Linux command that prints output to standard out. The variable can be any valid Bash variable name, following normal naming rules.

Now let‘s look at each substitution syntax more closely.

The preferred approach for command substitution is to use $() . This encapsulates the command in a way that allows easier nesting and mixing with other syntax.

Here is the syntax:

For example:

This runs cat /etc/passwd | wc -l to count user accounts, stores the number in users , and allows reuse of that result.

You can use $(command) anywhere in scripts where command notation is allowed. The output text replaces the $() when the line is evaluated.

Benefits of $() :

  • More readable for nested substitutions
  • Can be safely nested inside strings
  • Easier to mix quotes, double quotes, and substitution
  • Supports newlines in output
  • Often faster than backticks
  • Slightly newer, so older shell versions may not support

Another legacy syntax for command substitution is backticks ( `` ). This works similarly:

Here is an example:

This captures the number of home directories into $homedirs for later usage.

The backticks allow running any standard Linux command, execute it, replace the backticks with the command standard output, and store the result in the variable.

Benefits include:

  • Supported in virtually all Bash versions
  • Very lightweight syntax
  • Messes up nested quotes easier
  • Trivial to confuse with single quotes
  • No straightforward nesting of commands
  • No newlines in output values
  • Slower performance than $() in many cases

Overall $(command) should be preferred in most cases unless legacy shell compatibility requires backticks.

Command substitution is not the only way to work with output from Linux commands. Alternatives like piping and output redirection provide other options.

Here is a quick comparison:

Method Benefits Downsides
Pipes Lightweight, stream processing Only use once, complex nesting
Files Handle large data Slower, storage usage
Command substitution Reuse, scripting power Performance with large data, memory concerns

Pipes allow you to connect multiple commands by redirecting standard streams, so the output of one command feeds directly as input to another. This allows efficient passing of data without intermediate storage. Pipes let you avoid repetitive interchange of temporary files.

However pipes have limitations – the output of each stage can only be consumed once. So they don‘t allow reuse of results. Complex nested pipes can also become difficult to read.

Writing output to files can handle large data and avoids memory concerns. But this requires manual clean up, is slower, and lacks flexibility for script usage.

As an simple test, here is a comparison of the speed for different methods to count lines:

And benchmark results:

Method Time
Baseline 0.036s
Pipes 0.196s
$() Substitution 0.463s
File 0.428s

So pipes have great performance for streaming data between commands. But substitution requires spawning subshells and storing data in memory which adds overhead. Writing to files has disk I/O cost.

So consider the size of data and if persistence is needed when deciding between usage options.

While command substitution is convenient, take care with large data volumes or repetitive usage in loops.

Costs include:

  • Additional processes spawned
  • Memory copies of data
  • Multiplication in loops

Let‘s look at some performance best practices:

Stream data through pipes instead

When dealing with large sequential data, use pipes to stream between processes instead of storing in memory:

Append command output to files

Write to files to avoid duplication of large data in memory:

Subsample data

If sampling output is enough, limit rows/bytes with head / tail .

Avoid repetitions in loops

Extract data once before loops instead of redundant commands:

Keep these tips in mind to help balance convenience and performance!

Practical Examples

Let‘s look at some common examples of capturing Linux command output into Bash variables for scripting tasks.

Here is an example of assigning ls directory listings to a variable:

Or with backticks:

You now have the list of file names in the current directory stored in $files for further manipulation.

Some ideas:

  • Get count: echo "File count: ${#files[@]}"
  • Check specific file: if [[ " $files " =~ " myconfig.conf " ]]; then ...
  • In a for loop: for f in $files; do ...

Capture df output:

Now you can process the disk usage output instead of calling df -h repeatedly:

Other ideas:

  • Format into a cleaner output
  • Extract specific volume usage
  • Check for volumes over 90% full
  • Feed as input to generate graphs

Capture the current date in a reusable variable:

You can use $now in logging, filenames, reports easily:

Saves the date output once instead of calling date redundantly.

A key benefit of assigning command output to variables is you can further manipulate, parse, and process results before usage.

You can pipe the captured output to other Linux utilities like awk , sed , grep , sort , uniq etc.

Some examples:

You can also feed command substitution output as input to other commands:

In addition, consider using these tools for parsing and manipulating more complex output:

  • jq – JSON processing
  • pup – HTML processing
  • xidel – XML/HTML data extraction

The key point is that assigning to a variable gives you maximum flexibility to transform and prepare output for your scripts.

Here are some guidelines and best practices when assigning command output to variables:

Quote variable references to avoid issues like whitespace tripping you up:

Be aware commands may print errors/warnings to stderr which you likely want to ignore. Redirect if issues:

For newlines in output, $() handles them correctly, backticks do not:

Watch that syntax highlighters don‘t confuse backticks and single quotes

Use set -x to debug issues with substitution

Consider saving output to temp files instead if very large

Avoid expensive commands inside loops

Thinking about these practices as you use command substitution will help you avoid pitfalls!

Be cautious of these potential issues when assigning command output to variables:

No quotations – failing to quote variables leads to problems with filenames/paths with spaces:

Syntax confusing – Intermixing backticks, single quotes and doubles quotes gets messy quick:

Use $() for readability:

Performance issues – don‘t assume substitution is free. Storing 5 GB of file contents into a variable is slow and wasteful.

No error handling – Redirect STDERR on commands to avoid errors messing up script logic and variables.

Assumptions about output – Command output may change over time – don‘t assume fixed widths, columns or text.

Naming confusion – Reuse same variable names for different commands accidentally. Choose clear, specific names.

Being aware of these issues will help you tap the power of command substitution safely!

Assigning Linux command output to variables provides simple yet powerful capabilities for scripting tasks, processing text, and connecting commands. Both $() and backticks accomplish capturing STDOUT, with $() generally being preferred.

We covered numerous examples like storing directory listings, disk usage figures, dates and more into Bash variables for easy programmatic reuse. Keep best practices in mind, and you can replace tedious repetition of Linux commands with cleaner and more efficient variable references instead.

Command substitution is one of those fundamental building blocks for Bash scripting that enables more advanced workflows. Learn it well, apply it judiciously, and it will pay dividends in cleaner, faster shell scripts for years to come!

Similar Posts

Conda install requirements.txt – a complete professional guide.

The Anaconda distribution has skyrocketed in popularity among data science teams looking to standardize on an…

Sorting "du" Disk Usage Reports by Size – An In-Depth Guide for Linux Admins

As a Linux system administrator, having deep visibility into disk usage across servers is critical for…

ESP32 Pinout Reference – A Complete Guide for Full-Stack Developers

The popularity of Espressif‘s ESP32 chip continues rising thanks to its high performance, versatility, and low…

How to Throw Knives Effectively in Roblox Breaking Point

Breaking Point‘s intense free-for-all knife and gun battles demand peak player performance. While firearms seemingly provide…

Mastering Bold Text in LaTeX: An Advanced Guide for Developers

As a programmer working with LaTeX, having precise control over text formatting is critical for creating…

A Beginner‘s Guide to Python Scripting

Python is an incredibly versatile programming language used for everything from web development and data science…

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Linux distributions
  • Linux tutorials
  • Frequently Asked Questions
  • Linux HowTo’s
  • Linux Distro’s
  • Linux & Open Source News
  • Advertising on Unixmen
  • Become a Contributor
  • Unixmen collaborated with Unixstickers

Bash String Comparison: Comparing Strings in Shell Scripts

bash string comparison

String comparison is a crucial operation in bash scripting, essential for tasks ranging from simple conditional checks to complex text processing. This guide will explore various methods of comparing strings in bash, including equality checks, pattern matching, and lexicographical comparisons.

Basic String Comparison Operators

  • Equality (=) and Inequality (!=):

String Comparison Operators

  • Case-Insensitive Comparison:

Case-Insensitive Comparison

  • String Length Comparison:

String Length Comparison

Advanced String Comparison Techniques

  • Pattern Matching:

String Comparison Pattern Matching

  • Regular Expression Matching:

String Comparison regular expression matching

  • Lexicographical Comparison:

String lexicographical Comparison

  • Substring Check:

substring check

Best Practices

  • Always quote variables to prevent word splitting:
  • Use double brackets [[ ]] for enhanced functionality:
  • Be aware of case sensitivity in comparisons.
  • Use -z and -n for checking empty and non-empty strings.
  • Leverage pattern matching for flexible comparisons.

Common Pitfalls:

  • Forgetting to quote variables: When working with variables that contain spaces or other special characters, it’s crucial to enclose them in quotes to prevent the shell from interpreting them as separate arguments. Failure to do so can lead to unexpected behavior, such as word splitting issues, where the variable’s value is treated as multiple words.
  • Using = instead of == in double bracket conditions: In double bracket conditions, the = operator is used for assignment, while the == operator is used for comparison. Using = instead of == can result in unintended assignments and incorrect logical evaluations.
  • Neglecting case sensitivity in comparisons: Python is case-sensitive, meaning that “string” and “String” are considered different values. If you’re comparing strings without taking case sensitivity into account, you may encounter unexpected results. To perform case-insensitive comparisons, you can convert both strings to lowercase or uppercase before comparing them.
  • Misusing -z and -n operators: The -z operator tests if a string is empty, while the -n operator tests if a string is non-empty. Misusing these operators can lead to incorrect logical evaluations and unexpected behavior. It’s important to use the correct operator based on the specific condition you’re testing.

Performance Considerations

For large-scale string comparisons, consider using external tools like ‘grep’ or ‘awk’ for better performance.

Why You Should Learn Bash String Comparison

Mastering string comparison in bash is crucial for:

  • Input validation: Ensuring that user input is valid and meets the expected criteria is essential for preventing errors and security vulnerabilities. This involves checking for data types, ranges, and formatting.
  • Configuration parsing: Many applications require the ability to read and interpret configuration files. This involves parsing the file format (e.g., INI, JSON, YAML) and extracting the necessary values.
  • File and directory operations: Working with files and directories is a fundamental task in many programming applications. This includes creating, reading, writing, deleting, and managing files and directories.
  • Text processing and analysis: Text processing involves manipulating and analyzing text data. This can include tasks such as tokenization, stemming, lemmatization, and sentiment analysis.
  • Conditional execution in scripts: Conditional execution allows scripts to make decisions and perform different actions based on specific conditions. This involves using if-else statements, loops, and logical operators.

By grasping the final details of string comparison in bash, you can write more robust, efficient, and error-free shell scripts, enhancing your ability to automate tasks and process textual data effectively.

Similar Articles

https://www.namehero.com/blog/bash-string-comparison-the-comprehensive-guide

https://linuxize.com/post/how-to-compare-strings-in-bash

More Articles from Unixmen

Bash Script Example: Guide for Beginners
Bash: Concatenate Strings Easily with Our Simple Guide
A Guide to Using Bash Arrays: Examples

Latest Articles

bash string comparison

Linux Antivirus: Security in Open-Source OS

assignment variable bash

Bash Increment Variable: Increment and Decrement Variables

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

BASH: Basic if then and variable assignment

I'm used to csh, so this is kinda irritating having to use bash. What is wrong with this code?

  • if-statement
  • 1 That's not valid csh , either. –  chepner Commented Sep 17, 2013 at 18:11

By standard it should be

In normal shell scripts you use [ and ] to test values. There are no arithmetic-like comparison operators like > and < in [ ] , only -lt , -le , -gt , -ge , -eq and -ne .

When you're in bash, [[ ]] is preferred since variables are not subject to splitting and pathname expansion. You also don't need to expand your variables with $ for arithmetic comparisons.

Also, using (( )) for arithmetic comparisons could be best for your preference:

konsolebox's user avatar

  • Thanks. Crazy sensitive this bash is. I typed what you had, and got erors like ./read.sh: line 14: =0: command not found But when I copy and pasted your code directly, it worked. Do you have to always indent 3 spaces before "mod=2" ? –  Corepuncher Commented Sep 17, 2013 at 17:54
  • 2 @Corepuncher It's not necessary. Indent style is anyone's option in shell scripting. I think you tried to add $ to mod when assigning a value to it? $mod=0 . In bash it would be interpreted as an expansion of $mod which is an empty string plus =0 . –  konsolebox Commented Sep 17, 2013 at 18:06
  • 3 Bash needs to be sensitive about whitespace because something like FOO= bar is interpreted as running the command bar in an environment where FOO is set to the empty string. –  chepner Commented Sep 17, 2013 at 18:11
  • 1 will mod exist outside the scope of the if , if it hasn't been declared before? –  Mehdi Commented Oct 17, 2022 at 16:34
  • 1 @Mehdi Yes it will. –  konsolebox Commented Oct 18, 2022 at 18:09

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged bash if-statement or ask your own question .

  • The Overflow Blog
  • One of the best ways to get value for AI coding tools: generating tests
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • How to increase distance by a unit after every instance in Geometric Nodes array?
  • Why is steaming food faster than boiling it?
  • Is it defamatory to publish nonsense under somebody else's name?
  • On the history of algae classification
  • Concerns with newly installed floor tile
  • Are there something like standard documents for 8.3 filename which explicitly mention about the folder names?
  • Equation of Time (derivation Analemma)
  • The consequence of a good letter of recommendation when things do not work out
  • How can I switch from MAG to TRU heading in a 737?
  • Is downsampling a valid approach to compare regression results across groups with different sample sizes? If so, how?
  • Definition of annuity
  • How to reply to a revise and resubmit review, saying is all good?
  • Strange behavior of Polygon with a hole
  • ASCII 2D landscape
  • Color an item in an enumerated list (continued; not a duplicate)
  • Is it true that before European modernity, there were no "nations"?
  • AWK search for multiple patterns in a file
  • Doesn't nonlocality follow from nonrealism in the EPR thought experiment and Bell tests?
  • Why does a capacitor act as an open circuit under a DC circuit?
  • Longtable goes beyond the right margin and footnote does not fit under the table
  • Is there an essential distinction between experienced and observed consciousness?
  • Will "universal" SMPS work at any voltage in the range, even DC?
  • Looking for a short story on chess, maybe published in Playboy decades ago?
  • Why did early ASCII have ← and ↑ but not ↓ or →?

assignment variable bash

IMAGES

  1. How to Assign Variable in Bash

    assignment variable bash

  2. How to Set Variables in Bash: Shell Script Syntax Guide

    assignment variable bash

  3. How to Assign Variable in Bash Script? [8 Practical Cases]

    assignment variable bash

  4. How to Assign Variable in Bash Script? [8 Practical Cases]

    assignment variable bash

  5. How to Assign Variable in Bash Script? [8 Practical Cases]

    assignment variable bash

  6. How to Assign Variable in Bash Script? [8 Practical Cases]

    assignment variable bash

VIDEO

  1. Working with BASH shell

  2. Chapter 1 Sample Program

  3. learn bash data structure variable , array , list with vagrant and virtualbox

  4. Our Vison for VoteBash in 2025 with Martijn Atell

  5. How to Know your purpose

  6. Variable Assignment in R

COMMENTS

  1. How to Work with Variables in Bash

    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, my_name=Dave.

  2. How to Assign Variable in Bash Script? [8 Practical Cases]

    The first line #!/bin/bash specifies the interpreter to use (/bin/bash) for executing the script.Then, three variables x, y, and z are assigned values 1, 2, and 3, respectively.The echo statements are used to print the values of each variable.Following that, two variables var1 and var2 are assigned values "Hello" and "World", respectively.The semicolon (;) separates the assignment ...

  3. How to Use Variables in Bash Shell Scripts

    Using variables in bash shell scripts. In the last tutorial in this series, you learned to write a hello world program in bash. #! /bin/bash echo 'Hello, World!'. That was a simple Hello World script. Let's make it a better Hello World. Let's improve this script by using shell variables so that it greets users with their names.

  4. Assigning one variable to another in Bash?

    A=(a a a) declare -n VAR=A # "-n" stands for "name", e.g. a new name for the same variable. VAR+=(b) echo "${A[@]}" # prints "a a a b". That is, VAR becomes effectively the same as the original variable. Instead of copying, you're adding an alias. Here's an example with functions: function myFunc() {.

  5. Variable Declaration and Assignment

    In programming, a variable serves as a placeholder for an unknown value, enabling the user to store the different data and access them whenever needed.During compilation or interpretation, the symbolic names of variables are replaced with their corresponding data locations.This article will mainly focus on the variable declaration and assignment in a Bash Script.

  6. bash

    This technique allows for a variable to be assigned a value if another variable is either empty or is undefined. NOTE: This "other variable" can be the same or another variable. excerpt. ${parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

  7. Mastering Variable Assignment In Bash: Syntax, Manipulation, Scopes

    Understanding the basic syntax for assigning variables is crucial for writing effective Bash scripts. In this section, we will explore the different ways to assign values to variables in Bash. Using the equals sign (=) operator. The most common method of assigning a value to a variable in Bash is by using the equals sign (=) operator.

  8. How to Assign One Variable to Another in Bash

    Declare a Variable in Bash. To create a variable in the Bash shell, you must assign a value to that variable. Syntax: varname=value. Here, varname is the name of the newly created variable, and value is the value assigned to the variable. A value can be null. Let's look at an example. $ me=superman.

  9. How to Set Variables in Bash: Shell Script Syntax Guide

    Bash Variables: This tutorial offers a detailed look at Bash variables, including their declaration, assignment, and usage. These resources offer in-depth information about Bash variables and related topics, and can provide valuable insights as you continue your Bash scripting journey. Wrapping Up: Mastering Bash Variables

  10. 4.2. Variable Assignment

    Variable Assignment. the assignment operator (no space before and after) Do not confuse this with = and -eq, which test, rather than assign! Note that = can be either an assignment or a test operator, depending on context. Example 4-2. Plain Variable Assignment. #!/bin/bash. # Naked variables. echo.

  11. Bash Script: Set variable example

    Next, look at the examples below to see more practical examples of setting a variable in a Bash script. Bash Script: Set variable examples. Check out the examples below to see how to set variables within a Bash script. When you set a variable to execute a command, the command will be executed and the output is stored inside the variable.

  12. Linux Bash: Multiple Variable Assignment

    Using the multiple variable assignment technique in Bash scripts can make our code look compact and give us the benefit of better performance, particularly when we want to assign multiple variables by the output of expensive command execution. For example, let's say we want to assign seven variables - the calendar week number, year, month ...

  13. Assign values to shell variables

    Assign values to shell variables. ← Variables • Home • Default shell variables value →. Creating and setting variables within a script is fairly simple. Use the following syntax: varName= someValue. someValue is assigned to given varName and someValue must be on right side of = (equal) sign. If someValue is not given, the variable is ...

  14. Bash Variables Explained: A Simple Guide With Examples

    Bash is an untyped language, so you don't have to indicate a data type when defining your variables. var1=Hello. Bash also allows multiple assignments on a single line: a=6 b=8 c=9. Just like many other programming languages, Bash uses the assignment operator = to assign values to variables. It's important to note that there shouldn't be any ...

  15. Bash Variables (Bash Reference Manual)

    Assignment to this variable will not change the current directory. If DIRSTACK is unset, it loses its special properties, even if it is subsequently reset. EMACS ¶ If Bash finds this variable in the environment when the shell starts with value 't', it assumes that the shell is running in an Emacs shell buffer and disables line editing. ENV ¶

  16. Bash Assign Output of Shell Command To Variable

    To assign output of any shell command to variable in bash, use the following command substitution syntax: var =$ (command-name-here) var =$ (command-name-here arg1) var =$ (/ path / to / command) var =$ (/ path / to / command arg1 arg2) OR use backticks based syntax as follows to assign output of a Linux or Unix command to a variable: var ...

  17. How can I assign the output of a command to a shell variable?

    A shell assignment is a single word, with no space after the equal sign. So what you wrote assigns an empty value to thefile; furthermore, since the assignment is grouped with a command, it makes thefile an environment variable and the assignment is local to that particular command, i.e. only the call to ls sees the assigned value.. You want to capture the output of a command, so you need to ...

  18. Assigning default values to shell variables with a single command in bash

    Very close to what you posted, actually. You can use something called Bash parameter expansion to accomplish this. To get the assigned value, or default if it's missing: FOO="${VARIABLE:-default}" # FOO will be assigned 'default' value if VARIABLE not set or null. # The value of VARIABLE remains untouched.

  19. How to Assign Output of a Linux Command to a Variable in Bash

    Why Assign Command Output to a Variable. Here are some common reasons you may want to assign the output of a Linux command to a variable in Bash: Reuse output in scripts - Store command output in a variable so you can easily refer to it multiple times without re-running the command. This helps improve performance by avoiding redundant executions.

  20. Bash String Comparison: Comparing Strings in Shell Scripts

    String comparison is a crucial operation in bash scripting, essential for tasks ranging from simple conditional checks to complex text processing. This guide will explore various methods of comparing strings in bash, including equality checks, pattern matching, and lexicographical comparisons. Basic String Comparison Operators

  21. Dynamic variable names in Bash

    As Bash variables are identified by their name and not by their scope, you may inadvertently create an alias to itself (while thinking it would alias a variable from an enclosing scope). ... Assign to dynamic variable name in Bash. 4. Bash re-assignment of value to variable "command not found" 3.

  22. BASH: Basic if then and variable assignment

    In normal shell scripts you use [ and ] to test values. There are no arithmetic-like comparison operators like > and < in [ ], only -lt, -le, -gt, -ge, -eq and -ne. When you're in bash, [[ ]] is preferred since variables are not subject to splitting and pathname expansion. You also don't need to expand your variables with $ for arithmetic ...