|
|
|
Variables in shell scripts store values that can be referenced later. Unlike many programming languages, shell variables don’t require type declarations. |
|
|
To assign a variable, use |
|
|
To use a variable’s value, prefix it with |
|
|
You can also use curly braces for clarity, especially when the variable name could be ambiguous. |
|
|
Without braces, this would try to find a variable
named |
|
|
Variables can hold numbers too (as strings). |
|
|
You can reassign variables at any time. |
|
|
Variable names can contain letters, numbers, and underscores. They cannot start with a number. |
|
|
Unset variables expand to empty strings by default. |
|
|
Use |
|
|
Bash
Bash provides powerful string manipulation within parameter expansion: |
|
|
String length with ${#var}: |
|
|
Substring extraction with ${var:start:length}: |
|
|
Remove prefix with \({var#pattern} (shortest) or \){var##pattern} (longest): |
|
|
Remove suffix with \({var%pattern} (shortest) or \){var%%pattern} (longest): |
|
|
Search and replace with \({var/find/replace} (first) or \){var//find/replace} (all): |
|