Bash How to Save Output of a Command to a Variable


At times when writing a bash script you want to want to save the output of a command to a variable, in such case, you can use the following syntax.


Example 1: $() Syntax:

    vaiable_name = $(command)

    #!/bin/bash
    whoami_variable=$(whoami)
    echo $whoami_variable

    code2care

    Example - Save Command output to variable

Example 2: `` Syntax:

    vaiable_name = `command`

    #!/bin/bash
    whoami_variable=`whoami`
    echo $whoami_variable

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap