bash how to get result of command

Answer

To get get result of command you need to use command substitution (bash feature). Command substitution provides executing a bash command/commands and store its output to variable.

You can use special backticks (``). Everything what you write between backticks is executed by the shell before main command is executed. Sometimes people call them backquotes. Surely you know that they're under [Esc] key.

In this example, we get date into variable:

DATE=`date -I`
echo $DATE

If you expect multi-line output, and you would like to display it, it is good practice to use double quotes. In this example, we get all files in /etc into variable FILES:

FILES=$(ls /etc -l)
echo "$FILES"

What if you want to use backticks into backticks? It is a little trouble. The solution is to use dollar with brackets $(). This example does the same:

DATE=$(date -I)
echo $DATE

It is also possible to use inner way. In next example, output of date will be used as first echo argument:

echo `date -I`

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.