Skip to main content

Learn Bash Scripting

Chapter #6: How to Use Command Substitution and Output Redirection in Bash

In this chapter, you'll see how to improve your scripts by redirecting command output to files and using the output of one command in other commands.

In the previous chapters, we've covered some core concepts, like working with variables, taking user input, and writing simple scripts. Today, we're going to dive into something that will make your Bash scripting even more powerful: command substitution and output redirection.

Bash is a scripting language that makes automation and system administration both efficient and fun. With the right tools, you can automate almost anything on your Linux system, and today, we're introducing a couple of those tools.

Redirection is all about taking the output from one command and sending it somewhere else, like to another command or to a file. This might sound a bit tricky at first, but don't worry, we'll break it down step by step and show you how these techniques can make your scripts more flexible and dynamic.

Command substitution is a feature that allows you to capture the output of a command and use it inside another command, or store it in a variable. This lets you create scripts that can react to their environment and execute more efficiently.

By the end of this chapter, you'll know how to make your scripts more dynamic and useful by redirecting command output to files and using the output of one command in others.

Let’s get started!

Using Command Substitution in Bash

If you’ve been following along with the last few lessons, you might remember hearing about command substitution in one of the examples.

Every command in Bash produces an output, this is the result after executing the command. For instance, when you run the ls command, the output is the list of files in that directory. Command substitution allows us to capture that output and pass it to other tools, save it in a file, or use it however we need in our script.