Specifications and variables of shell scripts

Shell script overview

What is a shell?

Shell is a special application program, it is between the operating system kernel and the user, acting as a "command interpreter" role, responsible for receiving and interpreting the operating instructions (commands) entered by the user, and passing the operations that need to be performed Give the kernel execution and output the execution result.

Bash (/bin/bash) is the default shell used by most Linux versions.
The internal commands and operating environment of different shells are different.

Shell script concept

  • Save the commands to be executed to a text file in order
  • Need to give the file executable permissions
  • Can be combined with various Shell control statements to complete more complex operations

Shell script application scenarios

  • Repetitive operation
  • Interactive task
  • Bulk transaction processing
  • Service running status monitoring
  • Scheduled task execution

Shell script writing

Scripting code

  • Use vim text editor
  • When writing, each linux command is written in the order of execution (each command occupies a line)

Example:

vim /root/first.sh        #编辑一个脚本文件,一般脚本文件都以“.sh”结尾,方便辨识
#!/bin/bash               #脚本声明
#This is my first Shell-Script.    #注释信息
echo "当前的目录位置位于:"           #可执行语句
pwd

1.脚本申明(解释器):若第一行为“#!/bin/bash”,表示此行以下的代码语句是通过/bin/bash程序来解释执行,#!/bin/bash为默认解释器。还有其它类型的解释器,比如#!/usr/bin/python、#!/usr/bin/expect。
2.注释信息:以“#”开头的语句表示为注释信息,被注释的语句在运行脚本时不会被执行。
3.可执行语句:比如echo命令,用于输出" "之间的字符串

Insert picture description here

Shell script execution

Method 1: The command to specify the path requires the file to have x permission.

chmod +x /root/first.sh
指定绝对路径:/root/first.sh 
指定相对路径:./first.sh

Insert picture description here

Method 2: Specify Shell to interpret the script, and the file is not required to have x permissions.

sh 脚本路径:sh first.sh
source 脚本路径:. first.sh 或者 source first.sh

Insert picture description here

Redirection and pipeline operations

Pipe operation symbol "|"

The output result of the command on the left side of the pipe symbol "|" is used as the input (processing object) of the right command. Multiple pipes can be used in the same line of command.

Example:

ps aux | wc -l       #统计系统进程的总量
echo "123123" | passwd --stdin shangmo   #将用户zhangsan的密码改为123123

Insert picture description here

Redirect

Interactive hardware device

Standard input: receive data input by the user from the device.
Standard output: output data to the user through the device.
Standard error: report execution error information through the device

Types of Device file File 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
Types of Operator use
Redirect input < Read data from the specified file
Redirect output > Save the standard output result to the specified file, and overwrite the original content
>> Append the standard output result to the end of the specified file without overwriting the original content
Standard error output 2> Save the error information to the specified file and overwrite the original content
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
2>&1 Redirect standard error output to standard output

Example:

echo "123123" > pass.txt     #将123123定义到pass.txt文件中(此时文件中只剩下123123)
passwd --stdin shangmo < pass.txt    #读取pass.txt中的字符将其定义成shangmo用户的密码

ls -lh > log.txt 2>&1  等同于 ls -lh &> log.txt
本来ls -lh 直接输出的屏幕(等同于1指定屏幕)
执行>log后,是将标准输出结果保存到log.txt (1指向log.txt)
执行2>&1后,是将标准错误输出定义到标准输出信息中(2指向1,而1指向log.txt,因此2也指向了log.txt)

Insert picture description here

The role and types of shell variables

The role of variables

Function: used to store specific parameters (values) that the system and users need to use

Variable name: use a fixed name, preset by the system or user-defined
Variable value: can change according to user settings and changes in the system environment

Custom variable

  • Variable naming rules: start with a letter or underscore, case sensitive
    Format: variable name=variable value
  • View the value of the variable
    Format: echo $variable name

Example:

Product=Python   #将右边的变量值赋予左边的变量名,这里可以理解成Product=Python,但Python≠Product
version=4.0      #version=4.0,但4.0≠version

echo $product
echo $product $version

Insert picture description here

Use quotation marks when assigning values

双引号:允许通过$符号引用其他变量值
单引号:禁止引用其他变量值,$视为普通字符
反撇号:命令替换,提取命令执行后的输出结果,`..`和$(…)作用相同

Insert picture description hereInsert picture description here

Assign values ​​to variables from keyboard input

The read command gets the input

read -p "提示信息" 变量名
echo $变量名

Insert picture description here

Variable scope

  • 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 sub-Shell environment, local variables can no longer be used.
  • The specified variables can be exported as global variables through the internal command export, so that user-defined variables can continue to be used in all sub-Shell environments.

Format 1: export variable name
Format 2: export variable name=variable value

Insert picture description here
Insert picture description here

Operation of integer variables

格式:expr 变量1 运算符 变量2 [运算符 变量3]

常用运算符:
+     加法
-     减法
\*    乘法
/     除法
%     取余

Commonly used arithmetic expressions:

a=`expr 1 + 1 `
echo $((10 / (1+1)))
echo $[10 / (1+1)]
let a=12*5

相关概念补充:(现在先了解一下)
i++ 相当于 i=$[$i+1]
i-- 相当于 i=$[$i-1]
i+=2 相当于 i=$[$i+2]

Insert picture description hereInsert picture description here

Floating point operations

The bc command is a precision arithmetic tool that supports floating-point arithmetic, and of course integer arithmetic is also supported.

Format: bc [options] [parameters] #The parameter here refers to the file
#Many times use the pipe character to use the bc command

Example:

echo "1.1 + 2.2" >1.txt
cat 1.txt |bc

echo "1.1+2.2" | bc
echo "6.231-2.4" |bc
echo "scale=4;1.111*2.2" |bc
echo "scale=6;6.354/2.2" |bc

Insert picture description here

Environment variable

Concepts and configuration files

  • Environment variables are created in advance by the system to set the user’s working environment
  • Can be used to change or set an environment variable for a long time.
    The global configuration file is /etc/profile, and the variables defined in this file apply to all users.
    The user's own independent profile (~/.bash_profile), the variables defined in this file only apply to the current user.

Common variables and how to view

Use the env command to view the environment variables in the current working environment

Commonly used variables

  • USER represents the user name
  • HOME represents the user's home directory
  • LANG means language and character set
  • PWD represents the current working directory
  • PATH represents the default search path of executable programs
echo $PATH					#查看当前搜索路径
PATH="$PATH:/root"			#将/root目录添加到搜索路径
export PATH="$PATH:/root"	#输出为全局环境变量
message.sh

Edit a script file first
Insert picture description here
Insert picture description here
Insert picture description here

Read-only variable

Used when the variable value is not allowed to be modified,
readonly command to set read-only variable

readonly Product				#设置为只读变量
echo $Product
Product=abcd			        #只读变量不可以被重新赋值
unset Product					#只读变量不可以被删除,unset 命令用于删除变量,但无法删除只读变量,只能重启系统解决

Insert picture description here

Location variable

When executing a command line operation, the first field represents the name of the command or script program, and the remaining string parameters are assigned to the positional variables in order from left to right.

$n:n为数字,$0代表命令本身,$1-$9代表带一个到第九个参数,十以上的参数需要使用大括号表示,比如第十个参数为${10}

Insert picture description hereInsert picture description here
Insert picture description here

Predefined variables

$*、$@:表示命令或脚本要处理的参数。
$*:把所有参数看成以空格分隔的一个字符串整体,代表"$1 $2 $3 $4"。
$@:把各个参数加上双引号分隔成n份的参数列表,每个参数是独立的,代表"$1" "$2" "$3" "$4"。

$0:表示当前执行的脚本或命令的名称。
$#:表示命令或脚本要处理的参数的个数。	
$?:表示前一条命令或脚本执行后的返回状态码,返回值为0表示执行正确,返回任何非0值均表示执行出

Example:

vim mybak.sh
#!/bin/bash
time=backup-`date +%F`.tgz
tar zcf $time $* &> /dev/null	#/dev/null表示的是一个黑洞文件,通常用于丢弃不需要的数据输出
echo "已执行 $0 脚本,"
echo "共完成 $# 个对象的备份"
echo "具体内容包括: $*"

chmod +x mybak.sh
./mybak.sh /etc/passwd /etc/shadow

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/shengmodizu/article/details/114298645