Bash Scripting - Command Substitution
In this post, we'll discuss command substitution, which is essential for writing intelligent and efficient scripts. The basic idea behind command substitution is to save the output of a command in a variable. Below are some examples that demonstrate the effectiveness of this strategy.

Example 1: Keeping track of a command's output using ` `
[root@scriptbox scripts]# uptime
17:13:28 up 1 day, 8:32, 4 users, load average: 0.00, 0.01, 0.05
[root@scriptbox scripts]# UP='uptime'
[root@scriptbox scripts]# echo $UP
uptime
Now, let's take the output of the uptime command and store it using ` `:
[root@scriptbox scripts]# UP=`uptime`
[root@scriptbox scripts]# echo $UP 17:16:30 up 1 day, 8:35, 4 users, load average: 0.00, 0.01, 0.05
Example 2: Keeping track of a command's output using ()
[root@scriptbox scripts]# who
vagrant pts/0 2022-06-19 10:08 (10.0.2.2)
vagrant pts/1 2022-06-19 11:46 (10.0.2.2)
vagrant pts/2 2022-06-20 12:20 (10.0.2.2)
vagrant pts/3 2022-06-20 12:41 (10.0.2.2)
[root@scriptbox scripts]# user=$(who)
[root@scriptbox scripts]# echo $user
vagrant pts/0 2022-06-19 10:08 (10.0.2.2) vagrant pts/1 2022-06-19 11:46 (10.0.2.2) vagrant pts/2 2022-06-20 12:20 (10.0.2.2) vagrant pts/3 2022-06-20 12:41 (10.0.2.2)
Example 3: Storing a specific command output
Let's say we only want to save a portion of a command's output, rather than the entire output. Let's look at how we can accomplish this.
[root@scriptbox scripts]# free -m
total used free shared buff/cache available
Mem: 990 154 90 6 746 682
Swap: 1023 0 1023
We can filter the output result and save it to get the machine's used
memory:[root@scriptbox scripts]# free -m
total used free shared buff/cache available
Mem: 990 154 90 6 746 682
Swap: 1023 0 1023
[root@scriptbox scripts]# free -m | grep Mem
Mem: 990 154 90 6 746 682
[root@scriptbox scripts]# free -m | grep Mem | awk '{print $3}'
154
[root@scriptbox scripts]# USED_RAM=`free -m | grep Mem | awk '{print $3}'`
[root@scriptbox scripts]# echo $USED_RAM
154
[root@scriptbox scripts]# echo "Used RAM is $USED_RAM"
Used RAM is 154
Here is another example using script:
#!/bin/bash
echo "Welcome $USER on $HOSTNAME."
echo "++++++++++++++++++++++++++++++++++++++++++++"
FREERAM=$(free -m | grep Mem | awk '{print $4}')
LOAD=`uptime | awk '{print $11}'`
echo "#######################################################"
echo "Available free RAM is $FREERAM MB"
echo "#######################################################"
echo "Current Load Average $LOAD"
Result:
[root@scriptbox scripts]# ./command_subs.sh
Welcome root on scriptbox.
++++++++++++++++++++++++++++++++++++++++++++
#######################################################
Available free RAM is 87 MB
#######################################################
Current Load Average 0.01,