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 is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

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