KandZ – Tuts

We like to help…!

Linux CLI 65 🐧 Parameter expansion in shell scripts

a - what is parameter expasion in shell scripts part 1
Parameter expansion in a shell script allows you to manipulate variable values in various ways...
such as substring extraction, default value assignment, and pattern replacement.
common parameter expansions:
1. Substring Extraction:
${variable:position} → Extracts the substring from the specified position to the end.
${variable:position:length} → Extracts a substring of the specified length starting from the given position.
2. Default Value Assignment:
${parameter:-word}} → If parameter is unset or null, use word.
${parameter:=word} → If parameter is unset or null, assign it the value word.
3. Parameter Replacement:
${parameter+word} → If parameter is set, use word; otherwise, use an empty string.
${parameter?word} → If parameter is set, use its value; otherwise, print an error message and exit.

b - what is parameter expasion in shell scripts part 2
4. Length of a Parameter:
${#variable} → Returns the length of the variable.
5.Pattern Replacement:
${parameter/pattern/string} → Replaces the first occurrence of pattern with string.
${parameter//pattern/string} → Replaces all occurrences of pattern with string.
6. Remove Matching Prefix/Suffix:
${parameter#pattern} → Removes the shortest matching prefix.
${parameter##pattern} → Removes the longest matching prefix.
${parameter%pattern} → Removes the shortest matching suffix.
${parameter%%pattern} → Removes the longest matching suffix.

Leave a Reply