How do parameter expansions handle prefixes?

QuestionsQuestions8 SkillsProDec, 24 2025
0104

That's a great follow-up question! Just as the % operator handles the suffix (the end of a string), Bash uses the # operator to handle the prefix (the beginning of a string).

Here is how prefix expansion works:

1. The # Operator (Shortest Match)

The ${variable#pattern} syntax removes the shortest match of the pattern from the beginning of the string.

Example:
Imagine you have a variable representing a path:

file_path="Logs/system.log"
echo ${file_path#*/}
# Output: system.log
  • # looks at the start.
  • */ matches everything up to and including the first slash.

2. The ## Operator (Longest Match)

The ${variable##pattern} syntax removes the longest match of the pattern from the beginning. This is very common for extracting filenames from full paths.

Example:

full_path="/home/labex/project/script.sh"
echo ${full_path##*/}
# Output: script.sh
  • ##*/ matches everything from the start up to the last slash, leaving only the filename.

Summary Comparison

Direction Operator Description
Prefix (Start) # Remove the shortest match from the beginning.
Prefix (Start) ## Remove the longest match from the beginning.
Suffix (End) % Remove the shortest match from the end.
Suffix (End) %% Remove the longest match from the end.

A Pro-Tip for Memory:

  • # is on the left side of the $ key on a US keyboard (above '3'), and it deals with the beginning of the string.
  • % is on the right side of the $ key (above '5'), and it deals with the end of the string.

This makes parameter expansion a very powerful tool for string manipulation without needing to call external tools like sed or awk!

0 Comments

no data
Be the first to share your comment!