Shell Programming Specifications and Variables
1. An overview of Shell scripts
(1) The concept of Shell scripts
Save the commands to be executed in order to a text file
Give this file executable permissions
Shell control statements can be combined to complete more complex operations
vim first.sh #Write a first.sh's script file
(2) Shell script scenarios
Repeated operation
interactive tasks
Batch Transaction Processing
Service Running Status Monitoring
Timed Task Execution
......
(3) The Role of Shell - Command Interpreter, "Translator"
A shell is a special application that acts as a "command interpreter" between the operating system kernel and the user. It receives and interprets the operation instructions (commands) input by the user, passes the operations that need to be executed to the kernel, and outputs the results of the execution.
1. User's login Shell
Bash (/bin/bash) is the default Shell currently used by most Linux versions.
The internal instructions, operating environment, etc. of different shells will differ
(4) Write the first Shell script
1. Composition of Shell scripts
1. Script declaration (interpreter): If the first behavior'#!/bin/bash', the code statement below this line is interpreted by the / bin/bash program, #!/ Bin/bash is the default interpreter. There are other types of interpreters, such as #!/ usr/bin/python, #!/ usr/bin/expect.
2. Comment information: Statements beginning with'#'are expressed as comment information, and the commented statement will not be executed when the script is run.
3. Executable statements, such as echo commands, that output strings between ""
vim /root/first.sh
#!/bin/bash
echo "hello world"
2. Shell script execution
Method 1: The command specifying the path requires that the file have x privileges.
vim hello.sh
chmod +x hello.sh
Specify absolute path: /hello.sh
Specify relative path:. / hello.sh
Method 2: Specify a Shell to interpret the script without requiring that the file have x privileges.
SH script path: sh hello.sh
Sorce script path:. hello.sh or source hello.sh
(5) Pipelines and redirection
1. Pipeline operation
The output of the command on the left side of the pipe symbol'|'is used as input (processing object) to the command on the right side, and multiple pipes can be used in the same line of commands.
PS aux | wc-l #See how many processes there are
echo "abc123"| passwd --stdin zhangsan #Change password for three users
2. Redirection
Interactive Hardware Device | |||
---|---|---|---|
type | Device Files | File Description Number | Default device |
Standard Input | /dev/stdin | 0 | keyboard |
standard output | /dev/stdout | 1 | Monitor |
Standard error output | /dev/stderr | 2 | Monitor |
echo "123456" > pass.txt
passwd --stdin zhangsan < pass.txt
Ls-lh > log. Txt 2>&1 is equivalent to ls-lh &> log. Txt
Originally 1-->Screen (1 points to screen)
After executing > log, 1-->log. Txt (1 points to log.txt)
After executing 2>&1, 2-->1 (2 points to 1, and 1 to log.txt, SO 2 also points to log.txt)
2. Shell script variables
(1) Role of variables
Used to store specific parameters (values) that the system and users need to use
Variable name: Use a fixed name, defined by the system or user
Variable value: Ability to change according to user settings, system environment changes
(2) Classification of variables
Custom variables: defined, modified, and used by users themselves
Environment variables: Maintained by the system for setting up a work environment
Location variable: Pass parameters to the Scripter from the command line
Predefined variables: A class of variables built into Bash that cannot be modified directly
1. Custom Variables
Define a new variable
Variable names start with a letter or an underscore, case sensitive and recommended in all capitals
Format: variable name = variable value
PRODUCT=python
VERSION=2.7.13
View the value of a variable
Format: echo $variable name
echo $PRODUCT
echo $VERSION
echo "$PRODUCT"
echo $PRODUCT$VERSION
Use quotation marks when assigning values Double Quotes: Allow Pass Through $Symbol refers to other variable values (Need to put $Place in parentheses) Single quotation mark: no reference to other variable values. $Treat as Normal Character Inverse apostrophe: Command replacement, extract the output of the command after execution,`...`.and $(...)Same function
read command to get input
Method 1:
Read-p Hint variable name
echo $variable name
vim name.sh
Method 2:
Echo-n "Tips"
read variable name
echo $variable name
(3) Scope of the variable
By default, newly defined variables are only valid in the current Shell environment and are therefore called local variables. When you enter a subprogram or a new subshell environment, local variables are no longer available.
The specified variable can be exported as a global variable through the internal command export, enabling user-defined variables to continue to be used in all child Shell environments.
Format 1: export variable name
Format 2: export variable name = variable value
You can use the pgtree command to view the Shell environment.
Enter the bash command into the child Shell environment.
Press Ctrl+D key combination or enter exit command to exit child Shell environment
(4) Operation of integer variables
Format: expr variable 1 operator variable 2 [operator variable 3]
Operators: +addition, -subtraction, \*multiplication, /division,%redundancy
Common operation expressions:
i=$(expr 12 \* 5)
i=$((12 * 5))
i=$[12 * 5]
let i=12*5
I++ is equivalent to i=$[$i+1]
I--equivalent to i=$[$i-1]
i+=2 equals i=$[$i+2]
2. Environmental variables
Environment variables are created in advance by the system to set the user's working environment
Configuration file: /etc/profile, ~/. bash_profile
Use the env command to see the environment variables in your current working environment
The variable USER denotes the user name, HOME denotes the user's host directory, LANG denotes the language and character set, and PWD denotes the current working directory.
The variable PATH represents the default search path for an executable program
echo $PATH #View current search path
PATH="$PATH:/root"#Add/root directory to search path
export PATH="$PATH:/root"#Output as a global environment variable
hello.sh
The global configuration file for environment variables is/etc/profile, in which the variables defined act on all users. Each user also has his or her own separate profile (~/.bash_profile). It can be used to change or set an environment variable over a long period of time.
vim /root/.bash_profile
ExpoHISTSIZE=200 #Number of historical command records that modify the root user
echo $HISTSIZE
Source/root/. Bash_ Profile #Read and execute settings in the file
echo $HISTSIZE
3. readonly command to set read-only variables
product=benet
readonly product #set to read-only variable
echo $product
product=accp #Read-only variables cannot be reassigned
unset product #Read-only variables cannot be deleted. The unset command is used to delete variables
4. Location variables
When performing a command line operation, the first field represents the command name or script program name, and the remaining string parameters are assigned to the location variables in order from left to right.
$n:n is a number, $0 is the command itself, $1-
9 generation surface belt one individual reach No. nine individual ginseng number , ten with upper Of ginseng number need want send use large Include Number surface show , than as No. ten individual ginseng number by 9 Represents the first to ninth parameter, and more than ten parameters need to be braces, for example, the tenth parameter is </span><span class="katex-html"><span class="base"><span class="strut" style="height: 0.64444em; vertical-align: 0em;"></span><span class="mord">9</span><span class="mord cjk_fallback">generation</span><span class="mord cjk_fallback">surface</span><span class="mord cjk_fallback">belt</span><span class="mord cjk_fallback">one</span><span class="mord cjk_fallback">individual</span><span class="mord cjk_fallback">reach</span><span class="mord cjk_fallback">No.</span><span class="mord cjk_fallback">nine</span><span class="mord cjk_fallback">individual</span><span class="mord cjk_fallback">ginseng</span><span class="mord cjk_fallback">number</span><span class="mord cjk_fallback">,</span><span class="mord cjk_fallback">ten</span><span class="mord cjk_fallback">with</span><span class="mord cjk_fallback">upper</span><span class="mord cjk_fallback">Of</span><span class="mord cjk_fallback">ginseng</span><span class="mord cjk_fallback">number</span><span class="mord cjk_fallback">need</span><span class="mord cjk_fallback">want</span><span class="mord cjk_fallback">send</span><span class="mord cjk_fallback">use</span><span class="mord cjk_fallback">large</span><span class="mord cjk_fallback">Include</span><span class="mord cjk_fallback">Number</span><span class="mord cjk_fallback">surface</span><span class="mord cjk_fallback">show</span><span class="mord cjk_fallback">,</span><span class="mord cjk_fallback">than</span><span class="mord cjk_fallback">as</span><span class="mord cjk_fallback">No.</span><span class="mord cjk_fallback">ten</span><span class="mord cjk_fallback">individual</span><span class="mord cjk_fallback">ginseng</span><span class="mord cjk_fallback">number</span><span class="mord cjk_fallback">by</span></span></span></span></span>{10}</p>
vim addnum.sh
num1=$1
num2=$2
sum=$(($num1 + $num2))
echo $sum
./addnum.sh 12 34
$0 $1 $2
5. Predefined variables
$@and $*: Indicates the parameters to be processed by the command or script.
$*: Consider all parameters as a space-delimited string representing"$1 $2 $3 $4". $@: Separate parameters with double quotes n Copy of the parameter list, each parameter is independent, representing"$1" "$2" "$3" "$4". $0: Represents the name of the script or command currently executing. $#: Indicates the number of parameters to be processed by a command or script. $?: Represents a return status code after the execution of the previous command or script, with a return value of 0 indicating correct execution, and returning any non-zero value indicating an exception to execution. It is also often used Shell In scripts return Exit the function and return the exit value.Write a script to see the difference:
vim bianliang.shvim mybak.sh
#!/bin/bash
time=backup-date +%F.tgz
tar zcf $time $* &> /dev/null #/dev/null Represents a black hole file, usually used to discard unwanted data output
echo "executed $0 Script,"
echo "Total Completion $# Backup of objects
echo "Specific details include: $*"chmod +x mybak.sh
./mybak.sh /etc/passwd /etc/shadow