Linux put command output to variable

Bash Assign Output of Shell Command To Variable

Bash Assign Output of Shell Command To And Store To a Variable

To assign output of any shell command to variable in bash, use the following command substitution syntax:

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Bash
Est. reading time 2m

OR use backticks based syntax as follows to assign output of a Linux command to a variable:

Do not put any spaces after the equals sign and command must be on right side of = . See how to assign values to shell variables for more information.

Examples

Let us see some common examples for Linux, macOS, *BSD and Unix-like systems running bash.

BASH command output to the variable

To store date command output to a variable called now , enter:

To display back result (or output stored in a variable called $now) use the echo or printf command:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

You can combine the echo command and shell variables as follows:

You can do command substitution in an echo command itself (no need to use shell variable):

How to use multiline command

Try the following syntax:
my_var=$(command \
arg1 \
arg2 \
arg3 )
echo «$my_var»
For example,

Another ping command example for you:

Various ways to assign the output of a command to a shell variable

Conclusion

You learned how to assign output of a Linux and Unix command to a bash shell variable. For more information see GNU bash command man page here and read the following docs:

  • Command substitution – from the Linux shell scripting tutorial wiki.
  • See man pages: printf(1)

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

They might want to add it .bash_profile so it is persistent across reboots. Such as;

/.bash_profile
alias ll=’ls -l’
alias now=’date +%H:%M’
$ now
18:55

Error: printf “%s\n” now

Should be: printf “%s\n” “$now”

Thanks for the heads up!

i m trying to kill a process running on port say 4723…by using command “kill `lsof -t -i:4723`”…..it works fine..but i need to pass variable in lsof command instead of giving directly 4723…like..

var number = 4723;
“kill `lsof -t -i:number`”
is it possible…? and how..plz replyyy soon..thanks in advance

this is very helpful thank you

What about Piped command like
this?
ie.
droppedbyte=(iptables -L -v -n –line-number |grep DROP| awk ‘$1 = 5 ’)
or
droppedbyte=`iptables -L -v -n –line-number |grep DROP| awk ‘$1 = 5 ’`
Fail 🙁

-bash: syntax error near unexpected token `|’

This isn’t working because i used this “|”, need help

you are awesome 😀

This also worked.
droppedbyte=`iptables -L -v -n –line-number |grep DROP| awk ‘$1 = 5 ’`

Total shot in the dark Google search landed me here and this thing worked! Thanks a TON!

Thanks nixCraft — You just saved me a lot of time.

Am stuck in a shell script that stores a value recrusively when it runs to a variable.
when am running manually the value get stores but in crontab its not getting store.
please help me in this, below is my script.

Simple, concise, straighforward… excellent tutorial !

Many thanks… also saved me quite a bit of time !!

> var number = 4723;
>

varprt=4723 && lsofout=$(lsof -t -i:$varprt) && pidout=$(pidof $lsofout) && kill $pidout

Hi, can you assist ?

i’m trying to run the command softwareupdate -i -a then run one of 2 commands depending on the results (i’ve tried using the exit code but it gives a 0 if it fails under certain conditions)

this is what i’d scraped together but it doesn’t work and your examples look much simpler!

if [[ $var == *”Done.” || “No new software available” || “No updates are available.”* ]]
then
say woop woop

echo “updates failed”
say failed sad sad face
exit 1
fi

missed the top of!!

So i’ve got this do do what i need now, could you offer a more robust and tidier method ?

I was trying to get the Output of wget command in a varriable but its not storing it.

i am using it as
a=`wget -O ./google.jpg https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png`

when i am doing echo $a its shows blank

Please help me to store this in a varriable

This tutorial is opened a new world for me. 🙂 Fully automated nginx configurations with just a domain name input. I’ll save about 10-20 hours per month! You write the script once and use many times for different cases.
Thanks for this amazing tutorial!

You can perform assignment to multiple variables by eg doing something like this:

The redirect stdin from a shell command is quite useful, I’ve found.

Источник

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.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

BASH command output to the variable

Different types of bash commands need to be run from the terminal based on the user’s requirements. When the user runs any command from the terminal then it shows the output if no error exists otherwise it shows the error message. Sometimes, the output of the command needs to be stored in a variable for future use. Shell command substitution feature of bash can be used for this purpose. How you can store different types of shell commands into the variable using this feature is shown in this tutorial.

Command Substitution Syntax:

***Note: Don’t use any space before and after the equal sign when using the above commands.

Single command output to a variable

Bash commands can be used without any option and argument for those commands where these parts are optional. The following two examples show the uses of simple command substitution.

Example#1:

bash `date` command is used to show the current date and time. The following script will store the output of `date` command into $current_date variable by using command substitution.

Output:

Example#2:

`pwd` command shows the path of the current working directory. The following script stores the output of `pwd` command into the variable, $current_dir and the value of this variable is printed by using `echo` command.

Output:

Command with option and argument

The option and argument are mandatory for some bash commands. The following examples show how you can store the output of the command with option and argument into a variable.

Example#3:

Bash `wc` command is used to count the total number of lines, words, and characters of any file. This command uses -c, -w and -l as option and filename as the argument to generate the output. Create a text file named fruits.txt with the following data to test the next script.
fruits.txt

Run the following commands to count and store the total number of words in the fruits.txt file into a variable, $count_words and print the value by using `echo` command.

Output:

Example#4:

`cut` is another bash command that uses option and argument to generate the output. Create a text file named weekday.txt with seven-weekday names to run the next script.

weekday.txt

Create a bash file named cmdsub1.sh with the following script. In this script, while loop is used to read the content of weekday.txt file line by line and read the first three characters of each line by using `cut` command. After cutting, the string value is stored in the variable $day. Next, If the statement is used to check the value of $day is ‘Sun’ or not. The output will print ‘Sunday is the holiday‘ when if the condition is true otherwise it will print the value of $day.

cmdsub1.sh

Output:

Using command substitution in loop

You can store the output of command substitution into any loop variable which is shown in the next example.

Example#5:

Create a file named cmdsub2.sh with the following code. Here, `ls -d */` command is used to retrieve all directory list from the current directory. For loop is used here to read each directory from the output and store it in the variable $dirname which is printed later.

cmdsub2.sh

Output:

Using nested commands

How you can use multiple commands using pipe(|) is shown in the previous example. But you can use nested commands in command substitution where the output of the first command depends on the output of the second command and it works opposite of the pipe(|) command.

Nested command syntax:

Example#6:

Two commands, `echo` and `who` are used in this example as the nested command. Here, `who` command will execute first that print the user’s information of the currently logged in user. The output of the `who` command will execute by `echo` command and the output of `echo` will store into the variable $var. Here, the output of `echo` command depends on the output of `who` command.

Output:

Using Command path

If you know the path of the command then you can run the command by specifying the command path when using command substitution. The following example shows the use of command path.

Example#7:

`whoami` command shows the username of the currently logged in user. By default, this command is stored in /usr/bin/ folder. Run the following script to run `whoami` command using path and store in the variable, $output, and print the value of $output.

Output:

Using Command Line argument

You can use the command line argument with the command as the argument in the command substitution.

Example#8:

Create a bash file named cmdsub3.sh with the following script. `basename` command is used here to retrieve the filename from the 2 nd command line argument and stored in the variable, $filename. We know the 1 st command line argument is the name of the executing script which is denoted by $0.

Run the script with the following argument value.

Here, the basename of the path, Desktop/temp/hello.txt is ‘hello.txt’. So, the value of the $filename will be hello.txt.

Output:

Conclusion:

Various uses of command substitutions are shown in this tutorial. If you need to work with multiple commands or depended commands and store the result temporary to do some other tasks later then you can use this feature in your script to get the output.

More info in the video:

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Читайте также:  Samsung scx 3200 linux driver
Оцените статью