| by Arround The Web | No comments

How to Assign Output of a Linux Command to a Variable – bash

In Bash, it’s common to run Linux commands and capture their output for later use in a script. You can assign the output of a command to a variable by using command substitution, which is a feature of Bash that allows you to execute a command and replace it with its output. There are two ways to assign output to a variable and those are:

1: How to use Command Substitution to Assign Output of a Linux Command to a Variable

One way to assign the output of a Linux command to a variable in Bash is to use command substitution with the $() syntax and here is the complete syntax for it:

<variable-name>=$(command)

Here’s an example has been done which save the hostname command output in a variable using the syntax given above:

#!/bin/bash

# Assign the output of the 'hostname' command to the 'find_hostname' variable

find_hostname=$(hostname)

# Print the value of the 'hostname' variable

echo "Your hostname is:” $find_hostname

In this example, we used the hostname command to get the name of the current host, and then assigned the output to the find_hostname variable using command substitution. Finally, we printed the value of find_hostname variable using the echo command:

2: How to use Backticks to Assign Output of a Linux Command to a Variable

Another way to assign the output of a Linux command to a variable is to use backticks (`) instead of parentheses and below is the syntax for it:

<variable-name>=<`command`>

To further explain how to use this method I have given an example bash code that just reads the path or current directory.

#!/bin/bash

# Assign the output of the 'hostname' command to the 'find_hostname' variable

find_hostname=`hostname`

# Print the value of the 'hostname' variable

echo "Your hostname is:" $find_hostname

In this example, we used the pwd command to get the current working directory, and then assigned the output to the current_dir variable using backticks. Finally, we printed the value of the current_dir variable using the echo command:

Conclusion

Assigning the output of a Linux command to a variable is a common task in Bash scripting and can be accomplished using command substitution with either parentheses or backticks. By using these techniques, you can capture the output of a command and use it in your scripts to perform various tasks. You can use any of these three methods to assign the output of a Linux command to a variable in Bash, depending on your specific needs and preferences.

Share Button

Source: linuxhint.com

Leave a Reply