Bash Fu  ${%%}

Thanks to Gerrit for cluing me in.

In Bash, symbols like # and % aren’t just random noise—they are powerful operators used for Parameter Expansion. They allow you to “trim” or “slice” strings stored in variables without needing external tools like sed or awk.

To understand ${%%}, we have to break down how Bash sees those symbols.

  1. The Core Logic: Front vs. Back Think of these symbols as “knives” that cut parts of your string based on a pattern:
SymbolActionMnemonic
#Removes from the front (left)The # is on the left side of a standard keyboard (Shift+3).
%Removes from the back (right)The % is on the right side of the # (Shift+5).
  1. Doubling Up: Small vs. Large The number of symbols determines how “aggressive” the cut is:
  • Single (# or %): Non-greedy. It removes the shortest possible match.
  • Double (“ or %%): Greedy. It removes the longest possible match.
  1. Practical Examples Let’s say we have a variable: file="image.jpg.backup"

Using # and “ (Removing from the Front)

  • ${file#*.} → Result: jpg.backup (Cut the shortest bit ending in a dot).
  • ${file*.} → Result: backup (Cut everything up to the last dot).

Using % and %% (Removing from the Back)

  • ${file%.*} → Result: image.jpg (Cut the shortest bit starting from a dot at the end).
  • ${file%%.*} → Result: image (Cut everything from the first dot to the end).

If you have VAR="long.file.name.txt":

SyntaxLogicResult
${VAR#*.}Delete shortest match from frontfile.name.txt
${VAR*.}Delete longest match from fronttxt
${VAR%.*}Delete shortest match from backlong.file.name
${VAR%%.*}Delete longest match from backlong

Quick Tip: If you ever forget which is which, remember that on the keyboard, # is to the left of %. Therefore, # handles the left (start) of the string, and % handles the right (end).

Comments

Leave a Reply

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