Tecmint: Linux Howtos, Tutorials & Guides

How To Assign Output of a Linux Command to a Variable

When you run a command, it produces some kind of output: either the result of a program is suppose to produce or status/error messages of the program execution details. Sometimes, you may want to store the output of a command in a variable to be used in a later operation.

In this post, we will review the different ways of assigning the output of a shell command to a variable, specifically useful for shell scripting purpose.

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below:

Below are a few examples of using command substitution.

In this first example, we will store the value of who (which shows who is logged on the system) command in the variable CURRENT_USERS user:

Then we can use the variable in a sentence displayed using the echo command like so:

In the command above: the flag -e means interpret any escape sequences ( such as \n for newline) used. To avoid wasting time as well as memory, simply perform the command substitution within the echo command as follows:

Shows Current Logged Users in Linux

Next, to demonstrate the concept using the second form; we can store the total number of files in the current working directory in a variable called FILES and echo it later as follows:

Show Number of Files in Directory

That’s it for now, in this article, we explained the methods of assigning the output of a shell command to a variable. You can add your thoughts to this post via the feedback section below.

Previous article:

Next article:

Photo of author

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Related Posts

Rsync Command in Linux

How to Use Rsync Command in Linux: 16 Practical Examples

Clear RAM Cache and Swap in Linux

How to Clear RAM Memory Cache, Buffer and Swap Space on Linux

How to Create Users in Linux

How to Create Users in Linux [15 useradd Command Examples]

How to Compress Files in Linux

18 Tar Command Examples in Linux

List Systemd Running Services in Linux

How to List All Running Services Under Systemd in Linux

Linux sort command examples

7 Interesting ‘sort’ Command Examples in Linux – Part 2

10 thoughts on “How To Assign Output of a Linux Command to a Variable”

In my case it does not work for:

The command module list python writes to the command line:

Currently Loaded Modules Matching: python/3.7.4

You missed process substitution. For example: read uid gid < <(grep ^root /etc/passwd | awk -F: '{print $3 " " $4}') This allows you to set 2 or more variables if you mant.

Yap, how did i forget to mention this, it’s so helpful while writing scripts. Thanks for the reminder.

Why is $(…) preferred over `…` (backticks): http://mywiki.wooledge.org/BashFAQ/082

Many thanks for providing this useful link.

From the link Above “The backtick is also easily confused with a single quote.”

This happened in this article for the first figure.

@Depressing

True, it was a typo during publishing. We will modify the article as soon as possible. Thanks for the feedback.

Is there a way to store the result of the command ONLY if there is no error during the command ?

That is exactly what we explained in the article. To separate the result of a command from error messages, you can perform output/error redirection to files other than the screen. Then read the result from the file.

Read more about output redirection from here: https://www.tecmint.com/linux-io-input-output-redirection-operators/

Got something to say? Join the discussion. Cancel reply

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.

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

How to Save Command Output as Variable in Bash?

assign variable bash command output

  • Introduction

In bash scripts, assigning the output of a command to variables can be convenient by storing the outputs of the commands and using them later.

In this short guide, we will take a look at how you can store the output of a command as a variable in Bash.
  • The Basics To Set Up Variables

Saving the output of a command as a variable is achieved through command substitution . Command substitution is a wrapper that executes the command in a subshell environment , and replaces the wrapped command with the standard output of the environment in which the command was run. This output can then be referenced later, if connected to a reference variable!

Command substitution can be achieved through back ticks or the dollar sign with parentheses:

There's debate as to whether `command` (backticks) or $(command) (dollar sign and parentheses) should be used as the "best practice". $(command) works well in nesting, and improves readability in some cases, but you can go with either syntax in the preceding examples.

That being said - assigning the output of a command to a variable in Bash is as easy as:

Running ${variable} is known as parameter expansion , and is used to evaluate and fetch the value associated with a reference variable.

Let's now take a look at the simple example of setup a variable for a command to change the output color:

In the snippet, we've used the tput command and assigned the returned value of those commands to print colorful text. The setaf changes the foreground color, and 3 (green) and 9 (orange) are color codes.

Now we'll move on to another example that contains multiple conditions to set up variables for different commands:

In the above script, the whoami command returns the current user's username. The uname -a returns the system information, and the date returns the current time and date.

Note: We can chain variable assignment by adding multiple commands in a single nested call. The CREATE variable contains the output of the touch command, which in turn creates a file and sets the filename to the output of the date +"%d%m%Y command.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Finally, we add a multiline command variable assignment concept by adding a backslash (\) between the ls command -l flag to display only text files using *.txt . The backslash is an escape character that informs the shell not to interpret the next character.

In the echo command, we added the -e flag to use the special character, i.e., \n (newline), to print the output in the new line.

We get the following result after executing the script:

assign variable bash command output

In this short guide, we've taken a look at how you can set the output of a command to a variable in Bash. We've taken a look at the difference between the syntaxes for command substitution , noting the readability improvements of $(command) over backtick based substitution. Then, we've taken a look at several examples of both simple assignment and chained/nested output assignment.

You might also like...

  • Pimp my Terminal - An Introduction to "Oh My Zsh"
  • How to Parse Command Line Arguments in Bash
  • Guide to Understanding chmod
  • Get Total Size of a Directory in Linux
  • How to Permanently Set $PATH in Linux

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

In this article

Make clarity from data - quickly learn data visualization with python.

Learn the landscape of Data Visualization tools in Python - work with Seaborn , Plotly , and Bokeh , and excel in Matplotlib !

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013- 2023 Stack Abuse. All rights reserved.

How-To Geek

How to work with variables in bash.

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

Hannah Stryker / How-To Geek

Quick Links

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

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

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

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

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

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

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

my_name=Dave

my_boost=Linux

his_boost=Spinach

this_year=2019

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

echo $my_name

echo $my_boost

echo $this_year

Let's use all of our variables at once:

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

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

my_boost=Tequila

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

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

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

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

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

drink_of-the_Year="$my_boost $this_year"

echo drink_of_the-Year

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

Type this into a text file, and then save it as 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

Type the following to run the script:

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

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

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

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

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

You can reference command line parameters in a script just as you would regular variables. Let's modify our script, as shown below, and save it with the new name 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

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

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

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

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

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

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

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

First, save the following with the filename 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

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

./script_one.sh

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

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

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

site_name="How-To Geek"

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

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

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

Set Variable to Output of Command in Bash

Dataward Promo

  • Linux Howtos
  • Set Variable to Output of Command in …

Command Substitution in Bash

Bash command output to variable.

Set Variable to Output of Command in Bash

This tutorial demonstrates assigning the output of a command to a variable in bash using command substitution.

Command substitution is a bash feature that enables us to run Linux commands and store the command’s output in a bash variable. Once a command is executed using the command substitution syntax, the command’s standard output replaces the command, with any trailing newlines removed.

Command substitution uses two different syntaxes to store the command output to a variable.

The first syntax type puts the command inside the parenthesis and adds a $ sign at the beginning, as shown below.

Every character inside the parenthesis is treated as part of the command.

The second type of syntax uses backticks around the command.

We use the following examples to demonstrate command substitution in a bash script.

Below, we use the first syntax of parenthesis and a dollar sign at the beginning. The whoami command is executed, and the output replaces the command, which is then assigned to the user variable. We use the echo command to display the message to standard output.

Running this script displays the following output.

Below, we use the backticks syntax. The output of the whoami command is assigned to the user variable, and echo is used to print the message to the terminal.

Running the script displays the output below.

In the script below, we use ls to list the contents of the delftstack folder using the parenthesis and the dollar sign syntax. The output of the ls command is assigned to the files variable. The echo command is used to print out the content of the files variable to the terminal.

Running the script prints the following output to the standard output.

The below bash script uses the backticks syntax to assign the output of the ls command to the files variable, and the echo command is used to print the content of the files variable to the standard output.

Running the script displays the following output.

We use the following syntax to assign a multiline command to a variable in the bash script.

The bash script below demonstrates assigning the output of a multiline command to a variable. The ls command list all the contents of the current folder, and the output is piped to the head command. The head command only selects the first 5 lines of the input from ls and pipes the output to the grep command. The grep command matches the line with the word flow and prints it out to the standard output.

Fumbani Banda avatar

Fumbani is a tech enthusiast. He enjoys writing on Linux and Python as well as contributing to open-source projects.

Related Article - Bash Output

  • Bash Suppress Output

It's FOSS

Bash Basics Series #2: Using Variables in Bash

Abhishek Prakash

In the first part of the Bash Basics Series, I briefly mentioned variables. It is time to take a detailed look at them in this chapter.

If you have ever done any kind of coding, you must be familiar with the term 'variable'.

If not, think of a variable as a box that holds up information, and this information can be changed over time.

Let's see about using them.

Using variables in Bash shell

Open a terminal and use initialize a variable with a random number 4:

So now you have a variable named var and its value is 4 . Want to verify it? Access the value of a variable by adding $ before the variable name . It's called parameter expansion.

There must NOT be a space before or after = during variable initialization.

If you want, you can change the value to something else:

Using variables in shell

In Bash shell, a variable can be a number, character, or string (of characters including spaces).

Different variable types in Bash shell

Like other things in Linux, the variable names are also case-sensitive. They can consist of letters, numbers and the underscore "_".

Using variables in Bash scripts

Did you notice that I didn't run a shell script to show the variable examples? You can do a lot of things in the shell directly. When you close the terminal, those variables you created will no longer exist.

However, your distro usually adds global variables so that they can be accessed across all of your scripts and shells.

Let's write some scripts again. You should have the script directory created earlier but this command will take care of that in either case:

Basically, it will create bash_scripts directory if it doesn't exist already and then switch to that directory.

Here. let's create a new script named knock.sh with the following text.

Change the file permission and run the script. You learned it in the previous chapter.

Here's what it produced for me:

Using global variable in Bahs script

Did you notice how it added my name to it automatically? That's the magic of the global variable $USER that contains the username.

You may also notice that I used the " sometimes with echo but not other times. That was deliberate. Quotes in bash have special meanings. They can be used to handle white spaces and other special characters. Let me show an example.

Handling spaces in variables

Let's say you have to use a variable called greetings that has the value hello and welcome .

If you try initializing the variable like this:

You'll get an error like this:

This is why you need to use either single quotes or double quotes:

And now you can use this variable as you want.

Using spaces in variable names in bash

Assign the command output to a variable

Yes! You can store the output of a command in a variable and use them in your script. It's called command substitution.

Here's an example:

Command substitution in bash

The older syntax used backticks instead of $() for the command substitution. While it may still work, you should use the new, recommended notation.

Variables change the value unless you declare a 'constant' variable like this: readonly pi=3.14 . In this case, the value of variable pi cannot be changed because it was declared readonly .

🏋️ Exercise time

Time to practice what you learned. Here are some exercise to test your learning.

Exercise 1 : Write a bash script that prints your username, present working directory, home directory and default shell in the following format.

Hint : Use global variables $USER, $PWD, $HOME and $SHELL.

Exercise 2: Write a bash script that declares a variable named price . Use it to get the output in the following format:

Where X is the initial value of the variable price and it is doubled for tomorrow's prices.

Hint : Use \ to escape the special character $.

The answers to the exercises can be discussed in this dedicated thread in the community.

assign variable bash command output

In the next chapter of the Bash Basics Series, you'll see how to make the bash scripts interactive by passing arguments and accepting user inputs.

assign variable bash command output

Enjoy learning bash.

Abhishek Prakash

Created It's FOSS 11 years ago to share my Linux adventures. Have a Master's degree in Engineering and years of IT industry experience. Huge fan of Agatha Christie detective mysteries 🕵️‍♂️

Bash Basics Series #9: Functions in Bash

Bash basics series #8: for, while and until loops, bash basics series #7: if else statement, bash basics series #6: handling string operations, bash basics series #5: using arrays in bash, become a better linux user.

With the FOSS Weekly Newsletter, you learn useful Linux tips, discover applications, explore new distros and stay updated with the latest from Linux world

It's FOSS

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to It's FOSS.

Your link has expired.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.

LinuxSimply

Home > Bash Scripting Tutorial > Bash Variables > Variable Declaration and Assignment > How to Assign Variable in Bash Script? [8 Practical Cases]

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

Mohammad Shah Miran

Variables allow you to store and manipulate data within your script, making it easier to organize and access information. In Bash scripts , variable assignment follows a straightforward syntax, but it offers a range of options and features that can enhance the flexibility and functionality of your scripts. In this article, I will discuss modes to assign variable in the Bash script . As the Bash script offers a range of methods for assigning variables, I will thoroughly delve into each one.

Key Takeaways

  • Getting Familiar With Different Types Of Variables.
  • Learning how to assign single or multiple bash variables.
  • Understanding the arithmetic operation in Bash Scripting.

Free Downloads

Local vs global variable assignment.

In programming, variables are used to store and manipulate data. There are two main types of variable assignments: local and global .

A. Local Variable Assignment

In programming, a local variable assignment refers to the process of declaring and assigning a variable within a specific scope, such as a function or a block of code. Local variables are temporary and have limited visibility, meaning they can only be accessed within the scope in which they are defined.

Here are some key characteristics of local variable assignment:

  • Local variables in bash are created within a function or a block of code.
  • By default, variables declared within a function are local to that function.
  • They are not accessible outside the function or block in which they are defined.
  • Local variables typically store temporary or intermediate values within a specific context.

Here is an example in Bash script.

In this example, the variable x is a local variable within the scope of the my_function function. It can be accessed and used within the function, but accessing it outside the function will result in an error because the variable is not defined in the outer scope.

B. Global Variable Assignment

In Bash scripting, global variables are accessible throughout the entire script, regardless of the scope in which they are declared. Global variables can be accessed and modified from any script part, including within functions.

Here are some key characteristics of global variable assignment:

  • Global variables in bash are declared outside of any function or block.
  • They are accessible throughout the entire script.
  • Any variable declared outside of a function or block is considered global by default.
  • Global variables can be accessed and modified from any script part, including within functions.

Here is an example in Bash script given in the context of a global variable .

It’s important to note that in bash, variable assignment without the local keyword within a function will create a global variable even if there is a global variable with the same name. To ensure local scope within a function , using the local keyword explicitly is recommended.

Additionally, it’s worth mentioning that subprocesses spawned by a bash script, such as commands executed with $(…) or backticks , create their own separate environments, and variables assigned within those subprocesses are not accessible in the parent script .

8 Different Cases to Assign Variables in Bash Script

In Bash scripting , there are various cases or scenarios in which you may need to assign variables. Here are some common cases I have described below. These examples cover various scenarios, such as assigning single variables , multiple variable assignments in a single line , extracting values from command-line arguments , obtaining input from the user , utilizing environmental variables, etc . So let’s start.

Case 01: Single Variable Assignment

To assign a value to a single variable in Bash script , you can use the following syntax:

However, replace the variable with the name of the variable you want to assign, and the value with the desired value you want to assign to that variable.

To assign a single value to a variable in Bash , you can go in the following manner:

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.
  • single_variable.sh : Name of the file.

❸ Copy the script mentioned below:

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. Next, variable var_int contains an integer value of 23 and displays with the echo command .

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

❺ Use the following command to make the file executable :

  • chmod : changes 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.
  • single_variable.sh : File name to which the permissions are being applied.

❻ Run the script by using the following command:

Single Variable Assignment

Case 02: Multi-Variable Assignment in a Single Line of a Bash Script

Multi-variable assignment in a single line is a concise and efficient way of assigning values to multiple variables simultaneously in Bash scripts . This method helps reduce the number of lines of code and can enhance readability in certain scenarios. Here’s an example of a multi-variable assignment in a single line.

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

Script (multi_variable.sh) >

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 statements within a single line. The echo statement prints the values of both variables with a space in between. Lastly, the read command is used to assign values to var3 and var4. The <<< syntax is known as a here-string , which allows the string “ Hello LinuxSimply ” to be passed as input to the read command . The input string is split into words, and the first word is assigned to var3 , while the remaining words are assigned to var4 . Finally, the echo statement displays the values of both variables.

Multi-Variable Assignment in a Single Line of a Bash Script

Case 03: Assigning Variables From Command-Line Arguments

In Bash , you can assign variables from command-line arguments using special variables known as positional parameters . Here is a sample code demonstrated below.

Script (var_as_argument.sh) >

The provided Bash script starts with the shebang ( #!/bin/bash ) to use Bash shell. The script assigns the first command-line argument to the variable name , the second argument to age , and the third argument to city . The positional parameters $1 , $2 , and $3 , which represent the values passed as command-line arguments when executing the script. Then, the script uses echo statements to display the values of the assigned variables.

Assigning Variables from Command-Line Arguments

Case 04: Assign Value From Environmental Bash Variable

In Bash , you can also assign the value of an Environmental Variable to a variable. To accomplish the task you can use the following syntax :

However, make sure to replace ENV_VARIABLE_NAME with the actual name of the environment variable you want to assign. Here is a sample code that has been provided for your perusal.

Script (env_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The value of the USER environment variable, which represents the current username, is assigned to the Bash variable username. Then the output is displayed using the echo command.

Assign Value from Environmental Bash Variable

Case 05: Default Value Assignment

In Bash , you can assign default values to variables using the ${variable:-default} syntax . Note that this default value assignment does not change the original value of the variable; it only assigns a default value if the variable is empty or unset . Here’s a script to learn how it works.

Script (default_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The next line stores a null string to the variable . The ${ variable:-Softeko } expression checks if the variable is unset or empty. As the variable is empty, it assigns the default value ( Softeko in this case) to the variable . In the second portion of the code, the LinuxSimply string is stored as a variable. Then the assigned variable is printed using the echo command .

Default Value Assignment

Case 06: Assigning Value by Taking Input From the User

In Bash , you can assign a value from the user by using the read command. Remember we have used this command in Case 2 . Apart from assigning value in a single line, the read command allows you to prompt the user for input and assign it to a variable. Here’s an example given below.

Script (user_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The read command is used to read the input from the user and assign it to the name variable . The user is prompted with the message “ Enter your name: “, and the value they enter is stored in the name variable. Finally, the script displays a message using the entered value.

Assigning Value by Taking Input from the User

Case 07: Using the “let” Command for Variable Assignment

In Bash , the let command can be used for arithmetic operations and variable assignment. When using let for variable assignment, it allows you to perform arithmetic operations and assign the result to a variable .

Script (let_var_assign.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. then the let command performs arithmetic operations and assigns the results to variables num. Later, the echo command has been used to display the value stored in the num variable.

Using the let Command for Variable Assignment

Case 08: Assigning Shell Command Output to a Variable

Lastly, you can assign the output of a shell command to a variable using command substitution . There are two common ways to achieve this: using backticks ( “) or using the $()   syntax. Note that $() syntax is generally preferable over backticks as it provides better readability and nesting capability, and it avoids some issues with quoting. Here’s an example that I have provided using both cases.

Script (shell_command_var.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The output of the ls -l command (which lists the contents of the current directory in long format) allocates to the variable output1 using backticks . Similarly, the output of the date command (which displays the current date and time) is assigned to the variable output2 using the $() syntax . The echo command displays both output1 and output2 .

Assigning Shell Command Output to a Variable

Assignment on Assigning Variables in Bash Scripts

Finally, I have provided two assignments based on today’s discussion. Don’t forget to check this out.

  • Difference: ?
  • Quotient: ?
  • Remainder: ?
  • Write a Bash script to find and display the name of the largest file using variables in a specified directory.

In conclusion, assigning variable Bash is a crucial aspect of scripting, allowing developers to store and manipulate data efficiently. This article explored several cases to assign variables in Bash, including single-variable assignments , multi-variable assignments in a single line , assigning values from environmental variables, and so on. Each case has its advantages and limitations, and the choice depends on the specific needs of the script or program. However, if you have any questions 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 Float to Variable in Bash Script? [2 Methods]
  • 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 Variable Declaration and Assignment  | 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.

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.

Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.

Q&A for work

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

How do I set the output of a function as a variable value in a bash script?

I have the following function to count the number of files in a directory, within my bash script.

I'd like to use it repeatedly on different directories and save the count into a variable for each directory. Currently to do this, I use

I'm aware that I'm setting the no_of_files variable outside of the function each time, and would like to make it local to the function, not settign an intermediate variable in the main script. This is just in case there's some mistake meaning that the variable doesn't change between calls of the function (mistyping the function name maybe), and the old value of no_of _files is used.

If my function were:

How would I easily set these directory count variables?

  • command-line

Arronical's user avatar

  • So you are basically asking how a function may return a value in Bash? –  Byte Commander ♦ Sep 14, 2016 at 15:30
  • I guess so, I know it seems really stupid, and I know about the return keyword, but something doesn't seem to be working with my use of it. –  Arronical Sep 14, 2016 at 15:33
  • If I put return "no_of_files" at the end of the function, then reference it with $? I get a completely spurious value. –  Arronical Sep 14, 2016 at 15:35
  • just to point out, that you don't really need a function in this case, unless you reuse that same find+wc structure over and over. You also don't need pipe - find command has -exec flag to call external commands on files that it finds –  Sergiy Kolodyazhnyy Sep 14, 2016 at 15:53
  • @Serg tomorrows question will be about the best way to count the number of files in a directory! –  Arronical Sep 14, 2016 at 15:55

2 Answers 2

Bash functions are not like functions on other programming languages, they are more like commands. This means they have no classical return value, but

an exit/return code. This is an integer number in the range 0-255, where 0 means "success" and every other value represents an error. If you try to specify a number outside this range, it will be taken modulo 256 (add or subtract 255 from your number until it fits the range 0-255).

This code is automatically set to the return code of the last statement that got executed inside the function, unless you manually set it using the return command, like this:

output streams. Each Bash function can write arbitrary strings to the output streams (STDOUT and STDERR), just like normal scripts. The output can either be directly from the commands you run in the function, or set manually by using echo .

But instead of letting this output get displayed in the console, you can capture it when you run the function, e.g. using Bash's command substitution syntax, and store it in a variable in your main script:

So your code would have to look like this:

See Return value in bash script (on Stack Overflow) for more info.

Community's user avatar

  • Thanks, I realised that I was hideously over-complicating things as soon as you commented, but as I can't find anything like this on AU, I think it may be useful to other users in future. –  Arronical Sep 14, 2016 at 15:47
  • I also tried to use return to display the value of the variable, when this value was 633, it was returning 121, return can only display values between 0-255. $(( 633 % 256 )) = 121. –  Arronical Sep 14, 2016 at 15:51
  • That's just what I said. However, I'll add that numbers outside that range will be adapted using the modulo operation. –  Byte Commander ♦ Sep 14, 2016 at 15:55
  • Extraneous detail in my comment, I was just glad that I understood why I was getting that number. –  Arronical Sep 14, 2016 at 15:57

I'm a C++ programmer, so I like to mimic the " getter and setter " philosophy, where you use tiny little functions to get and set the value of a variable. I know there are some non-portable solutions out there like new versions of declare , but I like writing only portable code. The downside to using getters and setters is that you need to create a function (or two functions) for every value you want to manage. So... I made a "factory function" that handles creating getters/setters for you (below). Then, you just drop the equals sign for setting, and everything else looks pretty similar (see usage )... except now, you can pass "pointer-like things" into functions.

It does not require any particular shell (100% POSIX) with special features like indirection or namerefs , or the declare utility. You just pass in your variable name to makeGetSet , and your getter/setter function has that same name with a " Val " at the end (e.g. myVariableVal ). Tested with bash and dash .

For your specific question, you would use it like this:

Sean's user avatar

  • 1 I wish people would leave at least a brief comment with downvotes... I thought that this has been something lacking in the shell for DECADES now, and look how easy, powerful, and efficient it is once somebody has made the "factory function" for you !!! If anybody is still trolling, please tell me WHAT you don't like, so I can come up with something better !! Being able to do something like "pass by reference" to a function and change its value is a HUGE programming feature. –  Sean May 18, 2021 at 18:45

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged command-line bash scripts ..

  • The Overflow Blog
  • Behind the scenes building IBM watsonx, an AI and data platform sponsored post
  • One weird trick for teaching users your software
  • Featured on Meta
  • Seeking feedback on tag colors update
  • Site maintenance - Wednesday, December 13, 2023 @ 01:00 UTC (Tuesday,...
  • AI-generated content is not permitted on Ask Ubuntu

Hot Network Questions

  • What motivated the idea of the Tschirnhaus transformation of polynomial equations?
  • Is it possible for the coinbase transaction in block 164384 to be duplicated in block 1983702?
  • Can Lord Shiva give positions of all Gods including the position of Vishnu and Brahma?
  • What is the reason for N going back to the transformer station? Efficiency, practicability?
  • Matrix Class Implementation
  • Proof of remark in algebraic number theory
  • Collection of short sci-fi/alien stories, including a story about astronauts landing on a planet that seemed like Earth, but was slightly different
  • Auto Smooth Angle Isn't Working As Expected
  • Who do 五尺童子 and 而屠戮 refer to here?
  • When 'business' means 'company,' is it a countable noun?
  • Night hike partitioning
  • Sum of sinusoids at the same frequency but with different amplitudes and phases
  • Book with a guy with mismatched eyes who is sent to a boarding school for spies
  • Example of a uncountable compact metric space with countably infinitely many isometries
  • Proper use of "-ing" + "to: in the begging of a sentence
  • Accepted postdoc offer retracted last minute
  • UK crew working on cruise ship in Schengen area: does Seaman's Book stop passport being stamped at airport on arrival in the country before boarding?
  • My 1.5 time accomodations were not properly implemented, what can I do?
  • Why does grid voltage drop at 10pm?
  • Why won't Israel allow more aid into Gaza?
  • Can my boss sue me for handing in my notice
  • What is the meaning of the "Tall Trees" joke in Groundhog Day?
  • What range of altitudes would not be fatal for an astronaut falling from height on the moon?
  • Is my student applying to too many PhD programs in the US? (statistics / biostatistics)

assign variable bash command output

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

CyberITHub

How to Set/Assign output of a Linux Command to a Variable

In this article, I will go through different methods using which you can set/assign output of a Linux Command to a variable. If you are frequently using Bash Scripting then you might know or aware of the methods used to set/assign output of a Linux command to a variable but in case you are not then don't be afraid, we will see all the methods in great detail with examples in below section. But before that we need to understand what is variable in Linux ? Well, the definition of variable in Linux is not very different from what you already know from other Scripting or programming Languages.

In Linux also, variable is a string which is used temporarily store some values. The value assigned could be a number, text, filename, device, or any other type of data. But the way variables are used in Linux are little different from what you already know from other programming languages. In Linux, variables are broadly divided into two types - System defined variables and User defined variables.

System defined variables are the one which are predefined and generally managed and maintained by the Linux OS itself. For example - BASH, LOGNAME, OSTYPE, PWD, BASH_VERSION etc. These type of variables are available system wide and can be called and used from any place in Linux. You can use commands like set, env and printenv to check all the System defined variables.

The other set of variables are known as User defined variables which are managed and maintained by the User itself. In this types of variables, generally you don't need to define the data type of a variable and you also don't need to declare it before hand. These type of variables are mostly locally used and can be accessed only from within the terminal session you are currently working on. You can check more about variable assignment on Advanced Bash-Scripting Guide web page.

How to Set/Assign output of a Linux Command to a Variable

How to Set/Assign Output of a Linux Command to a Variable

Also Read: How to Change Time to Epoch Time Using date utility on Linux or Unix Server

Method 1: Using variable=$(command)

The first method that you can use to assign the output of a command to a variable using $(dollar) operator. You can put the command under dollar parenthesis and then assign it to variable like var in this case to store the output of the command. For example, here we are assigning the output of date +%s command to a variable called var using var=$(date +%s) from terminal as shown below. Then we are checking variable value using echo $var command to see if the command output is indeed getting stored or hold by the variable. So looks it does, hence this is one perfect and easy method that can be used to store or hold the command output.

You can also verify the output of variable by running the command manually and see if it shows the correct value.

Method 2: Using variable=`command`

This method is also not very much different from the previous one. It is just that instead of dollar and parenthesis you need to use single quote(` `) operator to store the command value to a variable. To show an example, we are using the previous command date +%s under single quote and then assigning this to a variable called var using var=`date +%s` command. Then displaying the value stored in the variable using echo $var command as shown below.

Like previous method, you can also verify here if the variable is showing correct value by running the command manually.

Popular Recommendations:-

How to Install jq(JSON Processor) on RHEL/CentOS 7/8 

How to Defragment an XFS Filesystem in Linux(5 Simple and Effective Steps)

How to Install Arpwatch tool on RHEL/CentOS 7/8(Simple and Effective Steps)

How to Install and Configure Squid Proxy Server on RHEL/CentOS 7/8

Python3: ModuleNotFoundError: No Module Named "prettytable" in Linux 

How to List all the Installed Python Modules in Linux{2 Easy Methods}

Solved: ModuleNotFoundError: No Module Named "requests" in Python 3

How to Install and Enable EPEL Repository on RHEL/CentOS 7/8{Simple and Easy Steps}

Leave a Comment Cancel reply

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

IMAGES

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

    assign variable bash command output

  2. Script Bash

    assign variable bash command output

  3. [Solved] How to assign an output to a shellscript

    assign variable bash command output

  4. How to Set/Assign output of a Linux Command to a Variable

    assign variable bash command output

  5. How to Save Bash Output to Variable? [4 Practical Cases]

    assign variable bash command output

  6. Bash Assign Output of Shell Command To Variable

    assign variable bash command output

VIDEO

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

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

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

  4. Video #7 Using Arithmetic Operator specific on Assignment Variable

  5. How to create a Bash Script to get User Data

  6. CODING TUTORIAL: LEARN IN JUST 5 MIN //ASSIGN VARIABLE

COMMENTS

  1. How do I set a variable to the output of a command in Bash?

    shell - How do I set a variable to the output of a command in Bash? - Stack Overflow How do I set a variable to the output of a command in Bash? Ask Question Asked 12 years, 11 months ago Modified 3 days ago Viewed 2.8m times 2385 I have a pretty simple script that is something like the following:

  2. bash

    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:

  3. How To Assign Output of a Linux Command to a Variable

    To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$ (command) variable_name=$ (command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...] arg1 arg2 ...' Below are a few examples of using command substitution.

  4. How to Save Command Output as Variable in Bash?

    That being said - assigning the output of a command to a variable in Bash is as easy as: VARIABLE=$ ( command ) echo "$ {VARIABLE}" Running $ {variable} is known as parameter expansion, and is used to evaluate and fetch the value associated with a reference variable.

  5. 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:

  6. How to Work with Variables in Bash

    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.

  7. Set Variable to Output of Command in Bash

    The bash script below demonstrates assigning the output of a multiline command to a variable. The ls command list all the contents of the current folder, and the output is piped to the head command. The head command only selects the first 5 lines of the input from ls and pipes the output to the grep command. The grep command matches the line with the word flow and prints it out to the standard ...

  8. bash

    to assign the output of a command to a variable while maintaining the possibility to check if the command was successful or not. In the following code, ls is only an example. The command I'm going to use is different. For the first part, normally, I would do something like this: { ls nonexistingfolder } && { echo "fine" } || { echo "error" }

  9. Bash Basics #2: Use Variables in Bash Scripts

    And now you can use this variable as you want. Assign the command output to a variable. Yes! You can store the output of a command in a variable and use them in your script. It's called command substitution. var=$(command) Here's an example:

  10. How to Store Command Output to Bash Variable? [3 Examples]

    You can easily set the output of a command on a variable and then print the value of that variable on the terminal. Here, I will save the output of the date command on the current_date variable and then print the variable value on the terminal. To know more, follow the below script. Steps to Follow > At first, launch an Ubuntu Terminal.

  11. How to Set Command Output to Variable in Bash [2 Methods]

    There are two common methods of setting the output of the Bash command into a variable. Command within a dollar sign or within a backtick is executed and stored in a variable. You can read the Comparative Analysis of Methods to find the easy one for you. Method 1: Substituting Command and Set in a Variable Using Dollar Sign

  12. How do I assign the output of a command to a variable?

    Is there a way to assign a value to a variable, that value which we get in terminal by writing any command? Example command: sensors From that we get CPU temperature. ... How can I store the output of an awk command as a bash script variable? 3. Make variables show a column with awk. 0. Can't assign function result to a variable. 0.

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

    #!/bin/bash my_function () { local x=10 # local variable assignment echo $x } my_function # Output: 10 echo $x # Output: (nothing, variable not defined outside the function) In this example, the variable x is a local variable within the scope of the my_function function.

  14. Bash: Assign output of pipe to a variable

    111 I am trying to get the output of a pipe into a variable. I tried the following things: echo foo | myvar=$ (</dev/stdin) echo foo | myvar=$ (cat) echo foo | myvar=$ (tee) But $myvar is empty. I don't want to do: myvar=$ (echo foo) Because I don't want to spawn a subshell. Any ideas?

  15. Capturing multiple line output into a Bash variable

    Capturing multiple line output into a Bash variable Ask Question Asked 14 years, 9 months ago Modified 9 months ago Viewed 354k times 686 I've got a script 'myscript' that outputs the following: abc def ghi in another script, I call: declare RESULT=$ (./myscript) and $RESULT gets the value abc def ghi

  16. Linux bash: Multiple variable assignment

    Linux bash: Multiple variable assignment Ask Question Asked 13 years, 11 months ago Modified 1 year, 5 months ago Viewed 182k times 159 Does exist in linux bash something similar to the following code in PHP: list ($var1, $var2, $var3) = function_that_returns_a_three_element_array () ;

  17. command line

    The output can either be directly from the commands you run in the function, or set manually by using echo. But instead of letting this output get displayed in the console, you can capture it when you run the function, e.g. using Bash's command substitution syntax, and store it in a variable in your main script:

  18. Linux Bash: Multiple Variable Assignment

    Take a closer look at how to do multiple variable assignment in Bash scripts. ... 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 ...

  19. How to Set/Assign output of a Linux Command to a Variable

    Method 1: Using variable=$ (command) The first method that you can use to assign the output of a command to a variable using $ (dollar) operator. You can put the command under dollar parenthesis and then assign it to variable like var in this case to store the output of the command.