English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
When defining a variable, do not add the dollar sign ($) before the variable name (it is required in PHP), for example:
your_name="w"3codebox.com"
Note that there should be no spaces between the variable name and the equal sign, which may be different from all programming languages you are familiar with. At the same time, the naming of variable names must follow the following rules:
The naming can only use English letters, numbers, and underscores; the first character cannot start with a number.
There should be no spaces in the middle; you can use underscores (_) instead.
You cannot use punctuation marks.
You cannot use keywords in bash (you can view reserved keywords using the help command).
The following are examples of valid Shell variable names:
w3codebox LD_LIBRARY_PATH _var var2
Invalid variable naming:
?var=123 user*name=w3codebox
Besides explicitly assigning values, you can also use statements to assign values to variables, such as:
for file in `ls /etc` or for file in $(ls /etc)
The above statements will /Loop through the filenames in the etc directory.
To use a defined variable, just add the dollar sign ($) in front of the variable name, for example:
your_name="qinjx" echo $your_name echo ${your_name}
Curly braces outside the variable name are optional; you can add them or not. The reason for adding curly braces is to help the interpreter identify the boundaries of variables, such as the following situation:
for skill in Ada Coffee Action Java; do echo "I am good at ${skill}Script" done
If you do not enclose the skill variable in curly braces and write echo "I am good at $skillScript", the interpreter will treat $skillScript as a variable (with an empty value), and the code execution result will not be as expected.
It is recommended to enclose all variables in curly braces, which is a good programming habit.
Variables that have been defined can be redefined, for example:
your_name="tom" echo $your_name your_name="alibaba" echo $your_name
This is a valid syntax, but note that you cannot write $your_name="alibaba" when assigning a value for the second time; the dollar sign ($) is only added when using variables.
The readonly command can be used to define a variable as a read-only variable; the value of a read-only variable cannot be changed.
The following example attempts to change a read-only variable and results in an error:
#!/bin/bash myUrl="https://www.google.com" readonly myUrl myUrl="https://www.oldtoolbag.com"
Run the script, the result is as follows:
/bin/sh: NAME: This variable is read only.
The unset command can be used to delete variables. Syntax:
unset variable_name
Variables that have been deleted cannot be used again. The unset command cannot delete read-only variables.
Example
#!/bin/sh myUrl="https://www.oldtoolbag.com" unset myUrl echo $myUrl
The above example will produce no output.
When running a shell, there are always three types of variables existing at the same time:
1) local variablesLocal variables are defined within scripts or commands and are only valid in the current shell session; other programs started by the shell cannot access local variables.
2) environment variablesAll programs, including those started by the shell, can access environment variables, and some programs need environment variables to ensure their normal operation. Shell scripts can also define environment variables when necessary.
3) shell variablesShell variables are special variables set by the shell program. Some of these variables are environment variables, and some are local variables, which ensure the normal operation of the shell
Strings are the most commonly used and useful data type in shell programming (apart from numbers and strings, there are not many other types to use), and strings can be enclosed in single quotes, double quotes, or not quoted at all.
str='this is a string'
Restrictions of single-quoted strings:
Any character inside single quotes will be output as is; variables inside a single-quoted string are invalid;
A single quote cannot appear alone in a single-quoted string (even after escaping the single quote), but it can appear in pairs as a string concatenation.
your_name='w3codebox' str="Hello, I know you are \"$your_name\"! \n" echo -e $str
The output is:
Hello, I know you are "w3codebox"!
Advantages of double quotes:
Variables can be inside double quotes
Escape characters can appear inside double quotes
your_name="w"3codebox # Use double quotes to concatenate greeting="hello, "$your_name" !" greeting_1="hello, ${your_name} !" echo $greeting $greeting_1 # Use single quotes to concatenate greeting_2='hello, '$your_name' !' greeting_3='hello, ${your_name} !' echo $greeting_2 $greeting_3
The output is:
hello, w3codebox ! hello, w3codebox ! hello, w3codebox ! hello, ${your_name} !
string="abcd" echo ${#string} # Output 4
The following example extracts a substring from the string starting at the 2 characters start from 4 characters:
string="w3codebox is a great site echo ${string:1:4} # Output unoo
Note: The index value of the first character is 0.
Find character i or o The position (which letter appears first is calculated):
string="w3codebox is a great site echo `expr index "$string" io` # Output 4
Note: In the above script, ` is the backtick, not the single quote 'Please don't get it wrong.
bash supports one-dimensional arrays (does not support multi-dimensional arrays) and does not limit the size of the array.
Similar to C language, the index of array elements starts from 0. To access elements in an array, you need to use an index, which can be an integer or an arithmetic expression, and its value should be greater than or equal to 0.
In Shell, arrays are represented by parentheses, and array elements are separated by "space" symbols. The general form for defining an array is:
array_name=(value1 value2 ... value_n)
For example:
array_name=(value0 value1 value2 value3)
or
array_name=( value0 value1 value2 value3 )
You can also define each component of the array separately:
array_name[0]=value0 array_name[1]=value1 array_name[n]=valuen
You can use non-continuous indices, and there is no limit to the range of indices.
The general format for reading array element values is:
${array_name[index]}
For example:
valuen=${array_name[n]}
Using the @ symbol, you can get all elements in the array, for example:}}
echo ${array_name[@]}
The method to get the length of an array is the same as that of getting the length of a string, for example:
# Get the number of array elements length=${#array_name[@]} # Or length=${#array_name[*]} # Get the length of a single array element lengthn=${#array_name[n]}
Lines starting with # are comments and will be ignored by the interpreter.
By adding a # symbol to each line # To set multi-line comments, like this:
#-------------------------------------------- # This is a comment # author: Basic Tutorial Website # site: www.oldtoolbag.com # slogan: Learn the basics, and you can go further! #-------------------------------------------- ##### User Configuration Area Start ##### # # # Add script description information here # # ##### User Configuration Area End #####
What should you do if you encounter a large amount of code that needs to be temporarily commented out during development and then uncommented later?
It's too tiring to add a # symbol to each line, so you can enclose this section of code to be commented with a pair of curly braces, define it as a function, and there is no place to call this function. This code will not be executed, achieving the same effect as comments.
Multi-line comments can also be used in the following format:
:<<EOF Comment Content... Comment Content... Comment Content... EOF
EOF can also be used with other symbols:
:<<' Comment Content... Comment Content... Comment Content... ' :<<! Comment Content... Comment Content... Comment Content... !