|
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 |
|
|
Output:
Hello, World! |
|
|
You can also use curly braces for clarity, especially when the variable name could be ambiguous. Without braces, this would try to create a file with the contents “variable” and not “world”. |
|
|
Output:
world |
|
|
Variables can hold numbers too, though they are generally treated as strings. |
|
|
Output:
The count is 42 |
|
|
You can reassign variables at any time, even to different types. In this example, we assign a string to a variable, reassign it to a number, and then reassign it to a string again. |
|
|
Output:
Hello, world! Hello, 42! Hello, world! |
|
|
Variable names can contain letters, numbers, and underscores. They cannot start with a number. |
|
|
Output:
variable_1: hello variable_2: world |
|
|
Unset variables expand to empty strings by default.
You can use |
|
|
Output:
Unset variable: '' Before unset: temporary After unset: '' |
|
|
Bash
Bash provides powerful string manipulation within parameter expansion. These features are not available in POSIX sh. A few examples of string manipulation:
|
|
|
Output:
Length: 13 Hello World! file.txt /home/user/docs archive hi hello hello hi hi hi |
|