Shell programming and variables

1, Overview

1. Concept

1) What is a shell:

shell It is a command interpreter, which is at the outermost layer of the operating system. It is responsible for directly talking with the user, interpreting the user's input to the operating system, processing various operating system output results, and outputting them to the screen for feedback to the user. This dialogue can be interactive or non interactive,The command we input is not recognized by the computer. At this time, a program is needed to help us translate it into a binary program recognized by the computer, and return the results generated by the computer to us.
  • Save the commands to be executed to a text file in order
  • Give the file executable permissions
  • Combine various shell control statements to complete more complex operations

2) What are shell scripts:

shel1 script means that when we put the original linux commands or statements in a file and then execute them through the program file, we say that the program is a shell script or shell

Procedures; We can enter a system command and related syntax statement combinations in the script, such as variables,
Process control statements, etc. combine them organically to form a powerful shell script

Summary: save the commands to be executed to a file and execute them in order. It does not need to be compiled. It is interpretive

3) What can shell scripts do

  • Automate the installation and deployment of software, such as the installation and deployment of LAMP architecture services
  • Complete the management of the system automatically, such as adding users in batch
  • Automate backups, such as scheduled database backups
  • Automated analytical processing, such as website traffic

4) Shell1 script usage scenario

When you need to complete a large number of complex and repetitive work, you don't need to repeat the command on the command line, just run the shell script directly, which greatly saves time and improves efficiency

2.shell function - command interpreter, "translator"

The shell in Linux system is a special application program, which is between the operating system kernel and the user
The shell in Linux system is a special application program, which is between the operating system kernel and the user. It acts as a "command interpreter", which is responsible for receiving and interpreting the operation instructions (commands) entered by the user, passing the operations to be executed to the internal core for execution, and outputting the execution results.

Interpreter: system software capable of executing programs written in other computer languages

There are many kinds of common shell interpreter programs. When using different shells, there will be some differences in internal instructions, command line prompt and so on. Through the / etc/shells file, you can understand the types of shell scripts supported by the current system.

[root@localhost ~]# cat /etc/shells
/bin/sh#It is the soft link of bash command (replaced by / bin/bash) / bin/bash is a shell developed under the framework of GNU.
/usr/bin/sh Have been bash Replaced.
/usr/bin/bash #centos and redhat systems use bash shell by default
/bin/tcsh #The enhanced version of csh is fully compatible with csh, integrates csh and provides more functions/ bin/csh has been replaced by / bin/bash (integrate c shell to provide more functions)

notes: nologin:strange shell,this shell Can prevent users from logging in to the host.
bash ( /bin/bash)It is the majority at present Linux Default for version shell. 
1)Why is it legal on our system shell To write/etc/shells This file?
This is because some services of the system will check what users can use during operation shells,And these shell The query is borrowed by/etc/ shells This file.

2)When can users get it shell Come to work?And which one will I get by default shell?
When I log in, the system will give it to me shell Let me work, and this login gets shell It's recorded in/etc/passwd In this file.
different shell With different functions, shell Also decided Linux Default in shell yes/bin/bash,fashionable shell have ash,bash,ksh,csh,zsh Wait, different shell All have their own characteristics and uses
 Most at present linux By default, the system uses bash

shell,Default login shell yes/bin/bash,Can view/etc/passwd Note in the document
 this shell It is for users and can be viewed/etc/passwd Which is the last field used shell,If you want to modify it, you can use chmod -s perhaps chsh -s To reassign

3. Script composition

First act"#!/ bin/bash ", script declaration (default interpreter): indicates that the following code statements in this line are executed through the / bin/bash program. There are other types of interpreters,

such as#! /usr/bin/python,#!/usr/bin/expect

Annotation information:with"#The statement at the beginning of "is expressed as annotation information. The annotated statement will not be executed when the script is running. The executable statement: such as echo command, is used to output the string between" "

Example:
vim first.shcd /boot/pwd
ls -lh vml*

Example:
#!/bin/bash
#This is my first shell-script.cd /boot
echo "The current directory is located at:"pwd
echo "Among them vml The first files include:"ls -lh vml*

4.shell programming specification

1. Creation steps:

1.Create a file containing command and control structures
2.Modify the permissions of this file so that it can be executed, chmod +x xxxx.sh
3.Detect syntax errors
4.implement  ./xxxx.sh

2. Script execution method:

Method 1:
Execute the script under the current path (absolute path and relative path) (with execution permission))
/home/first.sh perhaps./first.sh

Method 2:
sh . bash Script file Lu Jin (this method can not add execution permission to the script file))
bash first.sh or sh first.sh

Method 3: 
source Script file Lu Jin(You may not have execution permission)source first.sh

Method 4:Other methods
sh < first.sh perhaps cat first.sh |sh (bash)

5. Redirection and pipeline

1) Interactive hardware device

  • Standard input: receive user input data from the device
  • Standard output: output data to users through this device
  • Standard error: the device reports execution error information
type          Equipment file     Document description number    Default device
 Standard input      /dev/stdin    0             keyboard
 standard output       /dev/stdout   1             monitor
 Standard error output  /dev/stderr   2             monitor
Redirect operation:
type	      Operator	 purpose
 redirect input	 <	     Reads data from the specified file
 redirect output	 >	     Save the standard output results to the specified file and overwrite the original contents
 redirect output	 >>	     Append the standard output result to the end of the specified file without overwriting the original content
 Standard error output	2>	    Save the error message to the specified file and overwrite the original content
 Standard error output	2>>	    Append the error message to the end of the specified file without overwriting the original content
 Mixed output	 &>	     Save standard output and standard error to the same file
 Mixed output	 2>&1	 Redirect standard error output to standard output

2) Redirect output

Redirection output refers to saving the normal output result of the command to the specified file instead of directly displaying it on the screen of the display.
The redirection output uses the ">" or "> >" operator symbol to overwrite or append files, respectively
If the target file for redirection output does not exist, the file will be created, and then the output result of the previous command will be saved to the file; if the target file already exists, the output result will be overwritten or appended to the file.

>:It means that if there is content in the original file, the original content will be overwritten

>>:It means that if there is content in the original file, the newly added content will be added to it without overwriting the original content
 For example:
uname -p > kernel.txt

[root@localhost ~]# cat l.txt / / take the keyboard as the input device, which is also the system default 1234

[root@localhost ~]# cat <1.txt
1234
//Follow cat 1 Txt the result is the same, but this is based on 1 Txt file as input device

By default, cat The command will accept the input from the standard input device (keyboard) and display it to the console. However, if a file is used instead of the keyboard as the input device, the command will take the specified file as the input device and read and display the contents of the file to the console

[root@localhost ~]# cat << 0
//With o as the delimiter, as long as you do not enter o, you will always enter data and display it on the screen
>123
>456
>0
123
456
[root@localhost ~]# cat << 0 > a.txt
//Input redirection and output redirection can be combined to save the content output from the screen to the file > 123
>456
>0
[root@localhost ~]# cat a.txt
123
456
Example 1:Separate what is displayed incorrectly from what is displayed correctly
ls /etc/passwd XXXX
ls:cannot access xxx:There is no such file or directory
/etc/passwd
ls /etc/passwd xxx > a.txt
ls:cannot access xxx:There is no such file or directory
cat a.txt
/etc/passwd

ls /etc/passwd xxx 2> a.txt
/etc/passwd
cat a.txt
ls:cannot access xxx:There is no such file or directory
 notes:Use 2>Operators, like using>Overwrite the contents of the target file. If you append without overwriting the contents of the file, you can use 2>>Operator

Columns:
tar jcf /nonedir/etc.tgz /etc/ 2> error.log
cat /error.log

example:
In the automation script for compiling the source package, to ignore make,make install And other operation process information, it can be directed to an empty file/dev/null. 

# !/bin/bash 
#Automatically compile scripts for installing httpd servers
cd /usr/src/httpd-2.4.25/
./configure --prefix=/usr/local/httpd --enable-so &> /dev/null
make &> /dev/null
make install &> /dev/null 
#/dev/null is equivalent to make install > / dev/null 2 > & 1

Error redirection:
Error redirection refers to saving the error information (such as option or parameter errors) during the execution of a command to a specified file instead of directly displaying it on the screen. Error redirection uses the "2 >" operator

2 functions:
In practical application, error redirection can be used to collect the error information of program execution and provide basis for troubleshooting
You can also redirect unimportant error messages to the empty file / dev/null to keep the script output concise

When using the "2 >" operator, the contents of the target file will be overwritten as if using the ">" operator. If you want to append contents instead of overwriting the file, you should use the "2 > > operator instead

When the output result of the command may include both standard output (normal execution) information and error output information, you can use the operator ">" "2 >" to save the two types of output information to different files, or you can use the "& >" operator to save the two types of output information to the same file

3) Pipeline operation

Pipeline( pipe)Operation provides a mechanism for the cooperation between different commands, which is located in the pipeline symbol"|"The result of the command output on the left will be used as the input (processing object) of the command on the right),Multiple pipes can be used in the same command line.
stay shell In script applications, pipeline operations are usually used to filter the key information needed.
$bash $Indicates the system prompt, $Indicates that this user is an ordinary user, and the prompt of super user is#, bash is a kind of shell, which is the most commonly used shell under linux
$bash It means to execute a child shell,This son shell by bash.
example:
rpm -qa | grep httpd
grep "/bin/bash$" /etc/passwd | awk -F: '{print $1,$7 }'
column:
df -Th | grep "/$" | awk '{print $6}'
summary:
Redirection and pipeline operations are shell The functions commonly used in the environment, if skillfully mastered and flexibly used, will help to write concise but powerful code shell Script program

2, shell variable

Function and type of Shell variable

Role of variables

  • It is used to store specific parameters (values) required by the system and users
    • Variable name: a fixed name, preset by the system or defined by the user
    • Variable value: can change according to user settings and system environment

Type of variable

  • User defined variables: defined, modified and used by users
  • Special variables: environment variables, read-only variables, location variables, predefined variables

1. User defined variables

Definition of variables:

The variable operation in Bash is relatively simple and not as complex as other high-level programming languages (such as c/c + +, Java, etc.). When defining a new variable, you generally do not need to declare it in advance, but directly specify the variable name and assign it to the initial value (content)

format:Variable name=Variable value
 Variable name:A place where data is temporarily stored
 Variable value:Temporary changeable data

Permanent environment variable exists in~/.bashrc In the file (it will not disappear after power failure or restart), in each shell When starting, the permanent environment variable will be imported into shell And become shell Temporary environment variable, which can be unset After falling, but it will not affect others shell, Because we're going to talk about the difference shell The temporary environment variables are independent of each other.

There is no space on either side of the equal sign. The variable name should start with a letter or underscore, and the name should not contain special characters (e.g+,-,*,/, ., ?,%,&,#Etc.)
use echo View and reference the values of variables
 By adding a leading symbol before the variable name"$",You can reference the value of a variable, using echo Command can view variables in a echo View multiple variable values simultaneously in the command
 Example:
Product=Python
version=2.7.13
echo $Product$version
 When the variable name is easily confused with other characters immediately following it, braces need to be added"{}"Enclose it, otherwise you will not be able to determine the correct variable name. For undefined variables, null values are displayed
 Example:
echo ${Product}2.5
echo ${test}RMB
echo option
echo -n Indicates output without wrapping
 use echo -e Output escape characters and output the escaped content to the screen

Common escape characters are as follows:
\c:No newline output, in"\c"When there is no character after it, the function is equivalent to echo -n
\Line feed
\t:Insert after escape tab,Tab
 notes:\Escape character, following\The following special symbols will lose their special meaning and become ordinary characters.
as\s Will output"s"Symbols, not variable references
 example:
[root@localhost ~]#echo -n hello
hello [root@localhost ~]#

Undefine
unset Variable name

Special operation
 There are also some special assignment operations, which can assign values to variables more flexibly, so as to be suitable for various complex management tasks
 Double quotation mark("")
Double quotation marks are mainly used to define strings, especially when the content to be assigned contains spaces, they must be enclosed in double quotation marks;In other cases, double quotation marks can usually be omitted
1,When there are spaces in the content
echo "hello world"
echo nihao
2,When the value of a variable is assigned
[root@localhost ~]# version=2
[root@localhost ~]# pyver="python $version"
[root@localhost ~]# echo $pyver
python 2

Single quotation mark('')
When the content to be assigned contains $,",\And other characters with special meaning shall be enclosed in single quotation marks.
In the range of single quotation marks, the values of other variables cannot be referenced, and any characters are treated as ordinary characters. What you enter is displayed, but the assignment contains single quotation marks(')When, use\'Escape symbols to avoid conflicts.
[root@localhost ~]# test=123
[root@localhost ~]# echo "$test"
123
[root@localhost ~]# echo '$test'
$test

Apostrophe(``)
The undo number is mainly used for command replacement, allowing the screen output result of executing a command to be assigned to a variable. The range enclosed by the apostrophe must be an executable command line, otherwise an error will occur
ls -lh 'which useradd`
First pass which useradd Command found useradd Command, and then list the file properties according to the search results
date +number Y-%m-%d
[root@localhost ~]# time=`date +%T`
[root@localhost ~]# echo $time
04:23:22

It is difficult to implement nested command replacement in one line of command by using backapostrophe, so you can use it instead"$()"To replace the apostrophe operation to solve the nesting problem
rpm -qc $(rpm -qf $(which useradd))

2. The input content is variable assignment

Interactively define variables

read command
Use Bash's built-in command read to assign values to variables.
It is used to prompt users to enter information, so as to realize a simple interactive process. During execution, a line of content will be read from the standard input device (keyboard), and the read fields will be assigned to the specified variable in turn with a space as a separator (the redundant content will be assigned to the last variable). If only one variable is specified, the entire line is assigned to this variable.

[root@localhost ~]# read test
123        /Wait for user input and assign the entered value to test variable
[root@localhost ~]# echo $test
123

Generally speaking, in order to make the interactive operation interface more friendly and improve ease of use, the read command can be combined with the "- p" option to set the prompt information, so as to tell the user what content to enter and other related matters

[root@localhost ~]# read -p "please enter your name:" name
 Please enter your name:zhangsan
[root@localhost ~]# echo $name
zhangsan

Interactive definition variable (read)
-p prompt user information
-n defines the number of characters
-T defines the timeout time. If you don't enter it for more than a long time, you will exit automatically
-s does not display the content entered by the user. It is often used to enter the password read -s -p "input your password:" pass

Read from file and assign to variable
[root@server myscripts]# echo 192.168.100.100 > ip.txt
[root@server myscripts]# cat ip.txt
192.168.100.100
[root@server myscripts]# read -p "input your ip:" IP < ip.txt
[root@server myscripts]# echo $IP
192.168.100.100

Scope of variable

Global and local variables

By default, newly defined variables are only valid in the current shell environment, so they are called local variables when entering a subroutine or a new subroutine
Local variables can no longer be used in a shell environment

[root@localhost ~]# bash#Enter the sub shell environment
[root@localhost ~]# echo $name
[root@localhost ~]# echo $test

export command:
In order to enable user-defined variables to continue to be used in all sub shell environments and reduce repeated settings, you can export the specified variables as global variables through the internal command export.
You can specify multiple variable names as parameters at the same time (without using the "s" symbol), and the variable names are separated by spaces

[root@localhost ~]# exit
exit
[root@localhost ~]# export name test
[root@localhost ~]# bash
[root@localhost ~]# echo $name $testexit
zhangsan 123
 or
[root@localhost ~]# echo "$Product $version"
Benet 6.o
[root@localhost ~]# export Productversion #Export as global variable[root@localhost ~]# bash
[root@localhost ~]# echo "$Product $version"#The subroutine references the global variable benet6 0
[root@localhost ~]# exit

When exporting a global variable using export, you can also assign a value to the variable, so you don't need to assign a value in advance when defining a new global variable. env view the user's current environment variable
export ABC=123
You env can see it again
export -n ABC undefined global variable becomes local variable

3. Operation of numerical variables

In Bash shell environment, only simple integer operations can be performed, decimal operations are not supported, and integer operations are mainly performed through the internal command expr. There must be at least one space between the operator and the variable.

Operation contents: addition (+), subtraction (one), multiplication (*), division (/), remainder (%)
Calculation tool: ( ( ) ) and (()) and (()) and []
Operation commands: expr and let
Calculation tool: BC (provided by the system)

The common geometric operators of the expr command (which can not only operate, but also output to the screen) are as follows.

  • +: addition.
  • -: subtraction.
  • : multiplication operation. Note that "*" symbol cannot be used only, otherwise it will be regarded as file wildcard.
  • /: Division.
  • %: modular operation, also known as remainder operation, is used to calculate the remainder after numerical division.
Example:
[root@localhost~]# expr 1 + 1
2
[root@localhost~]# expr 1+1
1+1
[root@localhost~]# expr 2 * 2
expr:syntax error
[root@localhost~]# expr 2 \* 2  ##Multiplication * requires escape
4
[root@localhost~]# expr 2 '*' 2   ##Multiplication can also be expressed in single quotation marks, but it is not necessary because there is only one character
4

expr supports not only constants but also variable operations:

Example 1

[root@localhost ~]# X=35
[root@localhost ~]# Y=16
[root@localhost ~]# expr $X + 5
40
[root@localhost ~]# expr $X + $Y
51
[rootelocalhost ~]# expr $X - $Y
19
[root@localhost ~]# expr $X \* $Y
560
[root@localhost ~]# expr $X / $Y
2
[rootelocalhost ~]# expr $X % $Y
3

Example 2

sum=`expr $Y \*$Y \* $Y`
echo $sum

Example 3

#!/bin/ bash
#1. Define output data
read -p "Please enter the first number:" num1
read -p "Please enter the second number:" num2

#2. Perform addition operation
expr $num1 + $num2
echo "Summation number:$sumn"

[ ] and [] and [] and (()) must be used with echo because they can only operate and cannot output results

[root@localhost~]# echo $((1+1))
2
[root@localhost~]# echo $((5-2))
3
[root@localhost~]# echo $((a-b))
7
[root@localhost~]# echo $((b-a))  ##You can have negative numbers
-7

$[] integer operation

[root@localhost~]# echo $[10*10]      ##The * in $[] does not need to be escaped
100
[root@localhost~]# echo $[10%8]
2
[root@localhost~]# echo $[10/8]
1
[root@localhost~]# echo $[10/12]
0
[root@localhost~]# echo $[10%12]
10

[ ] change amount of transport count , can province slightly [ ] in of The operation of [] variables can be omitted from [] The operation of [] variables can be omitted from []

[root@client opt]# echo $[$a+$b]
13
[root@client opt]# echo $[a+b]
13
[root@client opt]# echo $[a-b]
7
[root@client opt]# echo $[a*b]
30
[root@client opt]# echo $[a/b]
3

4.let operation and bc operation

i++  ----  i=$[$i+1]
i--  ----  i=$[$i-1] 
i+=2 ----  i=$[$i+2]

let operation can change the value of the variable itself, but does not display the result. echo is required. Other operation methods can operate without changing the value of the variable itself

[root@localhost~]# n=1;let n=n+1;echo $n
2
[root@localhost~]# let n+=2   #Equivalent to n=n+2
[root@localhost~]# echo $n
4
[root@localhost~]# let n=n**2  #Exponentiation, the second power of 4
[root@localhost~]# echo $n
16
[root@localhost~]# let n++    #n self plus 1
[root@localhost~]# let n--l   #n minus 1
[root@localhost~]# echo $n
16
[root@localhost~]# echo $[n++]    #Output first and then increase by 1. At this time, the value of a has changed to
16
[root@localhost~]# echo $n        #Output the above value
17
[root@localhost~]# echo $[++n]      #First increase by 1 and then output, so the changed value is directly output
18
[root@localhost~]# echo $n
18

bc is used for operation. Decimal operation is supported, but it can not be used directly in the script. Otherwise, it will enter the interactive interface. echo can be used in combination with pipeline

[root@localhost ~]# bc
bc 1.06.95
copyright 1991-1994,1997,1998,2000,2004,2006 Free Software Foundation,Inc.This is free software with ABSOLUTELY NO WARRANTY.
For details type 'warranty'.
10/ 3
3
scale=3     #Specify the number of decimal places
10/3
3.333
[root@localhost ~]# echo "scale=3;10/3" | bc
3.333
[root@localhost ~]# echo "3^2" | bc   #Do the power operation and calculate the square of 3
9

Bcvariable operation:

[root@localhost ~]# a=10
[root@localhost ~]# b=3
[rootelocalhost ~]# echo "$a/$b" | bc
3
[root@localhost ~]# echo "scale=2; $a/$b" | bc
3.33
 You can try to calculate the area of the circle

bc can also perform logical operations. True is 1 and false is 0

[root@localhost ~]# echo "2>2"| bc
0
[root@localhost ~]# echo "2==2" | bc
1
[root@localhost ~]# echo "2<2"| bc
0
Common operational expressions:
i=$ (expr 12 \* 5)
i=$((12 * 5))
i=[12 * 5]
let i=12*5

i++   amount to i=$[$i+1]
i--   amount to i=$[$i-1]
i+=2  amount to i=$[$i+2]

5. Special variables

1) Environmental variables

Environment variable refers to a kind of variable created by Linux system in advance for operation needs. It is mainly used to set the user's working environment, including user host directory, command search path, user's current directory, login terminal, etc

The value of environment variables is automatically maintained by the Linux system and will change with the change of user status.
Use env command to view the environment variables in the current working environment. For some common environment variables, you should understand their respective uses.

For example,
The variable USER represents the USER name,
HOME indicates the user's host directory,
LANG stands for language and character set,
PWD indicates the current working directory,
PATH indicates the command search PATH, etc
RANDOM represents a RANDOM number and returns an integer of 0-32767,
USER indicates the account name of the current account, etc,

It is generally defined in all uppercase. Pay attention to distinguish it from user-defined variables

[root@localhost ~]# echo $RANDOM
20315
[roote1ocalhost ~]# echo $HOME
/root
[root@localhost ~]# echo $USER
root
[rootelocalhost ~]# echo $LANG
zh_cN.UTF-8
[rootelocalhost ~]# echo $SHELL
/bin/bash
[root@localhost -]# Echo $random in Linux, $random is used to generate a random number of 18945 from 0 to 32767
18945

PATH environment variable:
The PATH variable is used to set the default search PATH of the executable program. When only the file name is specified to execute the command program, the system will find the corresponding executable file in the directory range specified by the PATH variable. If it is not found, it will prompt "command not found"“

[root@localhost ~]# test.sh
bash: test.sh:Command not found...
[root@localhost ~]# echo $PATH
/usr/local/sbin:/usr/locai/bin:/usr/sbin:/usr/bin:/root/bin
[root@localhost ~]# pwd
/root

Because test SH is not in the directory of $PATH, so the system cannot recognize it and cannot use it directly. You need to follow the absolute PATH and use the script

Method 1:

Add the directory of the script to the $PATH
[root@localhost ~]# PATH="$PATH:/root"
//It's temporary,
Edit if permanently effective/etc/profile file
[root@localhost ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root
[root@localhost ~]# test.sh
hello world

Method 2:

Put your own script into P A T H in of some one individual order record stay L i n u x system Unified in , ring Boundary change amount of whole game match Set writing piece by / e t c / p r o f i l e , stay this writing piece in set righteousness of change amount do use to place have use household . except this of Outside , each individual use household still have since Oneself of single stand match Set writing piece (   / . b a s h p r o f i l e ) . repair change finish Yes want heavy new Ascend land just can living effect , as fruit Think stand Namely living effect , can with send use s o u r c e notes meaning : repair change A directory in PATH in Linux system, the global configuration file of environment variables is / etc/profile, and the variables defined in this file act on all users. In addition, each user has its own independent configuration file (~ /. bash_profile). After modification, you need to log in again to take effect. If you want to take effect immediately, you can use source. Note: modify A directory in PATH in Linux system, the global configuration file of environment variables is / etc/profile, and the variables defined in this file act on all users. In addition, each user has its own independent profile (/. bashp. P rofile). After the modification, you need to log in again to take effect. If you want to take effect immediately, you can use source. Note: modifying the PATH requires careful operation. If it is not found, it will affect the use of the command!!!

for example:
[root@localhost ~]# PATH=        #Manually set PATH to null
[root@localhost ~]# echo $PATH
[root@localhost ~]# ls
-bash: ls:There is no such file or directory

2) Read only variable

There is a special case in shell variables. Once set, its value cannot be changed. This variable is called read-only variable.
When creating a variable, you can set it as a read-only property, or set an existing variable as a read-only property,
Read only variables are mainly used when variable values cannot be modified. Read only variables cannot be changed or deleted

[root@localhost ~]# test=123
[root@localhost ~]# readonly test
#Readonly is used to define read-only variables. Once the variables defined with readonly are used, they cannot be changed in the script
[root@localhost ~]# echo $test
123
[root@localhost ~]# test=456
-bash: test:read-only variable 
[root@localhost ~]# unset test
-bash: unset: test:Can't unset:read-only variable
 Temporarily set, just exit the login to restore

3) Position variable

When the command line operation is executed, the first field represents the command name or script program name, and the other string parameters are assigned to the location variable in order from left to right.
Location variables, also known as location parameters, are represented by $1, $2, $3,..., $9
The name of the command or script itself is represented by "$0"

Example: write a simple script to create a user and password
[root@localhost ~]# vim user.sh
#!/bin/bash
useradd $1
echo $2 | passwd --stdin $1
##Exit the vim editor and execute the script
[root@localhost ~]# bash user.sh sj 123
 Change user sj Your password.
passwd:All authentication tokens have been successfully updated.
[root@localhost ~]# id sj
uid=1001(sj)gid=1001(sj)group=1001 (sj)

Example:
[rootelocalhost ~]# vim adder2num.sh
#!/bin/bash
SUM=`expr $1 + $2`
echo "$1 + $2 = $SUM"

[root@localhost ~]# chmod +x adder2num.sh
[root@localhost ~]# ./adder2num.sh 12 34 
#12 + 34 = 46 when $1 is 12 and $2 is 34
[root@localhost ~]# ./adder2num.sh 56 78 
#56 + 78 = 134 when $1 is 56 and $2 is 78


4) Predefined variables

Predefined variables are a kind of special variables pre-defined by Bash program. Users can only use predefined variables instead of creating new predefined variables or assigning values to predefined variables directly. Predefined variables are represented by a combination of the "$" symbol and another symbol

  • $#: indicates the number of positional parameters in the command line.
  • $*: indicates the contents of all location parameters, which are taken as a whole
  • $@: indicates that all location parameters are listed, but they are listed in a single form
  • $?: Indicates the return status after the execution of the previous command. A return value of 0 indicates that the execution is correct, and any non-0 value indicates that the execution is abnormal.
  • $0: indicates the name of the currently executing script or program
  • $$: indicates that the process number of the current process is returned
  • $!: Returns the process number of the last background process

Example: understand the meaning of each predefined and location variable according to a simple script

#!/bin/bash
echo $1
echo "$0 Indicates the name of the currently executing script or program"
echo "$# Indicates the number of positional parameters in the command line“
echo "$* The contents of all location parameters as a whole"
echo "$@ Indicates that all location parameters are listed, but they are listed in a single form

Example 2: you can optimize the script

#!/bin/bash
echo "The current script name is $0"
echo "The first parameter of the current script is $1"
echo "The second parameter of the current script is $2"
echo "The current script has $#Parameters“

Example 3 touch / home / KGC txt &

echo "$$  Indicates that the process number of the current process is returned"
echo "$?  0 Correct, 1 error"
echo "$!  Returns the process number of the last background process"

Understand the difference between $* and $@

  • ∗ , *, *, @: indicates the parameters to be processed by the command or script.
  • $*: all parameters are returned as a whole (single string) separated by spaces, representing "$1 $2 $3 $4".
  • $@: separate the parameters into n parameter lists with double quotation marks. Each parameter is returned as a string, representing "$1" "$2" "$3" "$4".

Add the following two lines to the script and execute

touch "$*"
touch "$@"

ls -l see which files were created

Summary:
$* is to treat all parameters as a whole
$@ treats each parameter as a separate individual

Set: view all system variables, including environment variables and user-defined variables (there is no command to view user-defined variables separately, you can set pipeline filtering)

Keywords: Linux Operation & Maintenance shell bash

Added by Thatsmej on Sun, 23 Jan 2022 23:04:42 +0200