YouTip LogoYouTip

Linux Shell Variable

# Shell Variables In Shell programming, variables are names used to store data values. When defining a variable, the variable name does not include a dollar sign ($, which is required in PHP), like this: ```bash your_name="tutorial" Note that there must be no space between the variable name and the equals sign. This might be different from all the programming languages you are familiar with. At the same time, variable names must follow these rules: * **Only contain letters, numbers, and underscores:** Variable names can contain letters (case-sensitive), numbers, and underscores `_`, but cannot contain other special characters. * **Cannot start with a number:** Variable names cannot start with a number, but can contain numbers. * **Avoid using Shell keywords:** Do not use Shell keywords (such as `if`, `then`, `else`, `fi`, `for`, `while`, etc.) as variable names to avoid confusion. * **Use uppercase letters for constants:** By convention, constant variable names usually use uppercase letters, for example, `PI=3.14`. * **Avoid using special symbols:** Try to avoid using special symbols in variable names, as they may conflict with Shell syntax. * **Avoid using spaces:** Variable names should not contain spaces, as spaces are typically used to separate commands and arguments. Valid Shell variable name examples: ```bash TUTORIAL="example.com" LD_LIBRARY_PATH="/bin/" _var="123" var2="abc" Invalid variable names: ```bash # Avoid using 'if' as a variable name if="some_value" # Avoid using special symbols like $ variable_with_$=42 ?var=123 user*name=tutorial # Avoid spaces variable with space="value" Avoid using spaces on both sides of the equals sign: ```bash # Correct assignment variable_name=value # May cause an error variable_name = value Besides explicit direct assignment, you can also assign values to variables using statements, like: ```bash for file in `ls /etc` or ```bash for file in $(ls /etc) The above statement will loop through the filenames in the `/etc` directory. --- ### Using Variables To use a defined variable, simply add a dollar sign before the variable name, like: ## Example ```bash your_name="qinjx" echo $your_name echo ${your_name} The curly braces outside the variable name are optional. Adding them or not is fine. Adding curly braces helps the interpreter identify the boundary of the variable, for example in the following situation: ## Example ```bash for skill in Ada Coffe Action Java; do echo "I am good at ${skill}Script" done If you don't add curly braces to the `skill` variable, writing `echo "I am good at $skillScript"`, the interpreter will treat `$skillScript` as a variable (whose value is empty), and the code execution result will not be what we expect. It is recommended to add curly braces to all variables; this is a good programming habit. Defined variables can be redefined, like: ## Example ```bash your_name="tom" echo $your_name your_name="alibaba" echo $your_name This is legal, but note that when assigning the second time, you cannot write `$your_name="alibaba"`. The dollar sign ($) is only added when using the variable. ### Read-only Variables Using the `readonly` command can define a variable as read-only. The value of a read-only variable cannot be changed. The following example attempts to change a read-only variable, resulting in an error: ## Example ```bash #!/bin/bash myUrl="https://www.google.com" readonly myUrl myUrl="" Running the script, the result is: /bin/sh: NAME: This variable is read only. ### Deleting Variables Using the `unset` command can delete a variable. Syntax: ```bash unset variable_name Once a variable is deleted, it cannot be used again. The `unset` command cannot delete read-only variables. **Example** ## Example ```bash #!/bin/sh myUrl="" unset myUrl echo $myUrl The above example will produce no output when executed. ### Variable Types Shell supports different types of variables. Some of the main types include: **String Variables:** In Shell, variables are usually treated as strings. You can use single quotes `'` or double quotes `"` to define a string, for example: ```bash my_string='Hello, World!' or ```bash my_string="Hello, World!" **Integer Variables:** In some Shells, you can use the `declare` or `typeset` command to declare integer variables. Such variables only contain integer values, for example: ```bash declare -i my_integer=42 This declaration tells Shell to treat `my_integer` as an integer. If you try to assign a non-integer value to it, Shell will attempt to convert it to an integer. **Array Variables:** Shell also supports arrays, allowing you to store multiple values in a single variable. Arrays can be integer-indexed arrays or associative arrays. Here is a simple example of an integer-indexed array: ```bash my_array=(1 2 3 4 5) Or an associative array: ```bash declare -A associative_array associative_array="John" associative_array=30 **Environment Variables:** These are special variables set by the operating system or the user, used to configure Shell behavior and affect its execution environment. For example, the `PATH` variable contains the paths where the operating system searches for executable files: ```bash echo $PATH **Special Variables:** There are some special variables in Shell that have special meanings, for example, `$0` represents the script's name, `$1`, `$2`, etc., represent the script's arguments. `$#` represents the number of arguments passed to the script, `$?` represents the exit status of the last command, and so on. --- ## Shell Strings Strings are the most commonly used and useful data type in Shell programming (besides numbers and strings, there aren't many other types to use). Strings can be enclosed in single quotes, double quotes, or no quotes at all. ### Single Quotes ```bash str='this is a string' Restrictions of single-quoted strings: * Any character inside single quotes will be output as is. Variables inside single-quoted strings are invalid. * A single, unpaired single quote cannot appear inside a single-quoted string (even if escaped), but they can appear in pairs for string concatenation. ### Double Quotes ## Example ```bash your_name="tutorial" str="Hello, I know you are "$your_name"! n" echo -e $str Output: Hello, I know you are "tutorial"! Advantages of double quotes: * Variables can be used inside double quotes. * Escape characters can appear inside double quotes. ### Concatenating Strings ## Example ```bash your_name="tutorial" # Using double quotes for concatenation greeting="hello, "$your_name" !" greeting_1="hello, ${your_name} !" echo $greeting $greeting_1 # Using single quotes for concatenation greeting_2='hello, '$your_name' !' greeting_3='hello, ${your_name} !' echo $greeting_2 $greeting_3 Output: hello, tutorial ! hello, tutorial ! hello, tutorial ! hello, ${your_name} ! ### Getting String Length ## Example ```bash string="abcd" echo ${#string} # Output 4 When the variable is a string, `${#string}` is equivalent to `${#string}`: ## Example ```bash string="abcd" echo ${#string} # Output 4 ### Extracting Substrings The following example extracts **4** characters starting from the **2nd** character of the string: ## Example ```bash string="tutorial is a great site" echo ${string:1:4} # Output unoo **Note**: The index of the first character is **0**. ### Finding Substrings Find the position of character **i** or **o** (whichever appears first is counted): ## Example ```bash string="tutorial is a great site" echo `expr index "$string" io` # Output 4 **Note:** In the above script, `` ` `` is a backtick, not a single quote `'`. Don't mistake it. --- ## Shell Arrays Bash supports one-dimensional arrays (does not support multi-dimensional arrays) and does not limit the size of the array. Similar to the C language, the index of array elements starts from 0. To access elements in an array, you use the index, which can be an integer or an arithmetic expression, and its value should be greater than or equal to 0. ### Defining Arrays In Shell, arrays are represented by parentheses, and array elements are separated by "spaces". The general form of defining an array is: ```bash array_name=(value1 value2 ... valuen) For example: ```bash array_name=(value0 value1 value2 value3) or ```bash array_name=( value0 value1 value2 value3 ) You can also define each component of the array individually: ```bash array_name=value0 array_name=value1 array_name=valuen You don't have to use consecutive indices, and there is no limit on the range of indices. ### Reading Arrays The general format for reading array element values is: ```bash ${array_name} For example: ```bash valuen=${array_name} Using the `@` symbol can get all elements in the array, for example: ```bash echo ${array_name[@]} ### Getting Array Length The method to get the array length is the same as getting the string length, for example: ## Example ```bash # Get the number of array elements length=${#array_name[@]} # Or length=${#array_name[*]} # Get the length of a single array element length=${#array_name} --- ## Shell Comments Lines starting with `#` are comments and will be ignored by the interpreter. Set multi-line comments by adding a `#` to each line, like this: ## Example ```bash #-------------------------------------------- # This is a comment # author: Tutorial # site: example.com # slogan: What you learn is not just technology, but also dreams! #-------------------------------------------- ##### User Configuration Area Start ##### # # # You can add script description information here. # # ##### User Configuration Area End ##### If during development, you encounter a large block of code that needs to be temporarily commented out and then uncommented later, what should you do? Adding a `#` to each line is too laborious. You can enclose the code block to be commented in a pair of curly braces, defining it as a function. If this function is not called anywhere, this block of code will not be executed, achieving the same effect as a comment. ### Multi-line Comments **Using Here Documents** Multi-line comments can also use the following format: ```bash :<<EOF Comment content... Comment content... Comment content... EOF In the above example, `:` is a null command, used to execute the Here document that follows. `<<'EOF'` indicates the start of the Here document, `COMMENT` is the identifier of the Here document. Content between these two identifiers will be treated as a comment and will not be executed. `EOF` can also be replaced with other symbols: ## Example ```bash : <<'COMMENT' This is a comment section. It can have multiple lines. COMMENT : <<' Comment content... Comment content... Comment content... ' : <<! Comment content... Comment content... Comment content... ! **Directly Using the `:` Command** We can also use the colon `:` command and enclose multiple lines of content with single quotes `'`. Since the colon is a null command, this content will not be executed. The format is: `:` + space + single quote. ## Example ```bash : ' This is a comment section. It can have multiple lines. '
← Docker Tutorial - Getting StarLinux File Content Manage β†’