0
0
Bash Scriptingscripting~10 mins

String suffix removal (${var%pattern}) in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - String suffix removal (${var%pattern})
Start with variable var
Apply suffix pattern match
Remove shortest matching suffix
Return modified string
End
The shell checks the variable's value, finds the shortest suffix matching the pattern, removes it, and returns the result.
Execution Sample
Bash Scripting
filename="report.txt"
result=${filename%.txt}
echo "$result"
Removes the shortest suffix '.txt' from the variable 'filename' and prints the result.
Execution Table
StepVariable 'filename'PatternActionResulting ValueOutput
1report.txt%.txtCheck if suffix '.txt' matchesMatches suffix '.txt'
2report.txt%.txtRemove shortest matching suffix '.txt'report
3reportN/AEcho the resultN/Areport
4reportN/AEnd of scriptN/A
💡 Suffix '.txt' removed; no more matches; script ends.
Variable Tracker
VariableStartAfter suffix removalFinal
filenamereport.txtreport.txtreport.txt
resultN/Areportreport
Key Moments - 2 Insights
Why does only the shortest suffix matching the pattern get removed?
Because the '%' operator removes the shortest suffix matching the pattern, as shown in execution_table step 2 where only '.txt' is removed, not more.
What happens if the pattern does not match the suffix?
No removal happens; the variable stays the same. This is implied because the action only removes when a match is found (step 1 and 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'result' after suffix removal?
A.txt
Breport
Creport.txt
Dreport.tx
💡 Hint
Check execution_table row 2 under 'Resulting Value' column.
At which step does the script output the final result?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table row 3 under 'Output' column.
If the variable was 'archive.tar.gz' and pattern was '%.gz', what would be the result after removal?
Aarchive.tar
Barchive
Carchive.tar.gz
Dtar.gz
💡 Hint
Remember '%' removes shortest matching suffix; see concept_flow and execution_table logic.
Concept Snapshot
Syntax: ${var%pattern}
Removes shortest suffix matching pattern from var's value.
Useful to strip file extensions or suffixes.
Only removes if pattern matches suffix.
Does not change original variable unless reassigned.
Full Transcript
This example shows how to remove a suffix from a string variable in bash using ${var%pattern}. The shell looks at the variable's value, finds the shortest suffix matching the pattern, removes it, and returns the modified string. For example, with filename="report.txt" and pattern '%.txt', the suffix '.txt' is removed, resulting in 'report'. The script then echoes this result. If the pattern does not match, the string remains unchanged. This is a simple way to strip file extensions or other suffixes in bash scripting.