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:
Here’s an example has been done which save the hostname command output in a variable using the syntax given above:
# 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:
To further explain how to use this method I have given an example bash code that just reads the path or current directory.
# 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.