Skip to main content

Learn Bash Scripting

Chapter #5: How to Use Globbing Characters in Bash Scripts

In this article, we will show you how to use globbing characters like *, ?, and [] to make file searches faster in your Bash scripts.

By now, you've learned how to write and run your first Bash script, how to use and declare variables, and how to work with user input. In this chapter, we’re going to unlock some cool tricks to make your Bash scripts even more powerful and flexible.

When you're working in the terminal (also known as the command line), you're basically talking to your Linux system using Bash commands. These commands can be typed one by one, or you can put them into a script to run them all at once. Either way, the system does what you tell it to.

Now, Bash isn’t just about running commands, it also gives you some handy shortcuts and special symbols that help you get things done faster. These are known as globbing characters, and they’re used a lot in real-world scripts.

At first, they might look a little weird, but once you get the hang of them, they’ll save you tons of time.

In this lesson, we’ll break down these special charactersβ€”like *, ?, and [], so you’ll understand exactly how they work and when to use them. Trust me, once you know how to use these properly, you’ll feel like a Bash wizard.

Globbing Magic in Bash

Globbing characters are very useful to match a set of files or directories, and there are several globbing characters that we can use in Bash.

The first one is the asterisk (*) character.

Using the Asterisk (*)

One of the most powerful and commonly used globbing characters in Bash is the asterisk (*), which is a little star that tells Bash to match zero or more characters of any kind.

Let’s say you’re inside a directory, and you want to list all the files and folders that start with the letter g, followed by anything else (or even nothing at all).

Here's how you can do it: