You can assign the output of a shell command to a variable in bash by using command substitution. Command substitution is achieved using either the backtick (`
) or the dollar sign and parentheses ($( )
).
Here’s an example using the backtick syntax:
output=$(ls)
This will assign the output of the ls
command to the variable output
.
And here’s an example using the dollar sign and parentheses syntax:
output=`ls`
Both of these syntaxes are equivalent, and you can use either one. Once you have the output assigned to a variable, you can use it in your script as you would any other variable.
For example:
output=$(ls)
echo "The contents of the current directory are: $output"
This script will run the ls
command and assign its output to the output
variable. It then uses the echo
command to print the contents of the output
variable, effectively printing the contents of the current directory.