What Does the Percent Sign in Linux Shell Strings Do?


0

what-does-the-percent-sign-in-linux-shell-strings-do-00

When you are in the process of learning how to fully use the Linux shell, you may find yourself curious about how much you can manipulate strings in order to get the best results. With that in mind, today’s SuperUser Q&A post has the answer to a curious reader’s question.

Today’s Question & Answer session comes to us courtesy of SuperUser—a subdivision of Stack Exchange, a community-driven grouping of Q&A web sites.

The Question

SuperUser reader Nissim Kaufmann wants to know what the percent sign in Linux shell strings does:

When using the Linux shell, what does the percent sign (%) do? For example:

what-does-the-percent-sign-in-linux-shell-strings-do-01

What does the percent sign in Linux shell strings do?

The Answer

SuperUser contributor Marek Rost has the answer for us:

When the percent sign (%) is used in the pattern ${variable%substring}, it will return content of the variable with the shortest occurrence of substring deleted from the back of the variable.

This function supports wildcard patterns, that is why it accepts an asterisk (star) as a substitute for zero or more characters. It should be mentioned that this is Bash specific. Other Linux shells do not necessarily contain this function.

If you want to learn more about string manipulation in Bash, then I highly suggest reading the following page, Advanced Bash-Scripting Guide: Chapter 10. Manipulating Variables. Among many other handy functions, it explains what a double percent sign (%%) does, for example.

I forgot to mention that when it is used in the pattern $((variable%number)) or $((variable1%$variable2)), the percent sign (%) character will function as a modulo operator.

When the percent sign (%) is used in different contexts, it should be recognized as a regular character only.


Have something to add to the explanation? Sound off in the comments. Want to read more answers from other tech-savvy Stack Exchange users? Check out the full discussion thread here.

Image Credit: Linux Screenshots (Flickr)


Like it? Share with your friends!

0

0 Comments

Your email address will not be published. Required fields are marked *