Command Substitution in Bash

In this article, we will explain what command substitution is, provide examples of its usage, and demonstrate how it can be used to create robust shell scripts.
Command Substitution in Bash

On this page

Command substitution allows you to use the output of a command as an argument to another command or variable assignment. This is useful when you need to dynamically set values based on system information or external commands.

In this article, we will explain what command substitution is, provide examples of its usage, and demonstrate how it can be used to create robust shell scripts. Understanding command substitution is key for any intermediate or advanced Bash user who wants to unlock the full potential of shell scripting.

Using Command Substitution in Bash Scripting

There are two methods for command substitution in bash:

  • $( )
  • Using backticks ``

Consider the following example:

today=$(date +%F)

echo "Today's date is $today"

This code executes the date command, captures its output, and assigns it to the $today variable. The $today variable is then displayed using the echo command.

Without command substitution, the code would look like this:

today=date +%F
echo "Today's date is $today"

This would print the literal string "date +%F" instead of executing the date command and capturing its output.

Here are some examples of using command substitution:

  • Set variables dynamically based on system info:
count=$(ls | wc -l)

dirsize=$(du -sh /home)
  • Use command output as arguments to other commands:
grep "foo" $(find . -name '*.txt')

tar -cvzf $(date +%F).tar.gz /mydir

Conclusion

In this short article, we have covered the basics of command substitution in Bash - including the syntax, use cases, and examples. You should now have a solid understanding of how to capture command output and pass it to other commands or variables in your Bash scripts. With this technique, you can make your scripts more dynamic and flexible to suit your specific needs. Command substitution unlocks the many possibilities of combining Linux utilities, so be sure to explore all the ways it can be applied in your own Bash scripting.

Subscribe to sysxplore newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox. It's free!
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!