SHELL script - variable

Posted by davey10101 on Wed, 15 Dec 2021 02:58:04 +0100

SHELL script - variable

SHELL script introduction

Programming language classification

Compiled language

  • Before the program is executed, it needs to be compiled into machine language and run the compiled results directly. The program has high execution efficiency, depends on the compiler, and has poor cross platform performance. Such as C, C + +. Suitable for low-level development or large-scale application or operating system development.

Interpretative language

  • The program does not need to be compiled. When running, it is translated into machine language by the interpreter. It is translated once every execution, which has low efficiency and good cross platform performance. Such as Python/JavaScript/ Perl /ruby/Shell, etc. It is applicable to some server scripts and some auxiliary interfaces, projects with low speed requirements and compatibility requirements for various platforms.

shell overview

  • shell is a bridge of human-computer interaction. It is used to parse commands and give them to the system kernel, so as to realize the management of physical hardware

  • Common shell

[root@server1 ~]# cat /etc//shells
/bin/sh       yes bash Shortcut to
/bin/bash     Linux default shell,Almost contains shell All functions
/usr/bin/sh   
/usr/bin/bash
/sbin/nologin Non interactive shell,Unable to log in to the operating system

shell script

  • Save the commands to be executed into the script according to a certain format and syntax, and execute them in order to realize specific functions

  • Applicable scenario: repetitive and complicated work

    • Automated backup
    • Batch deployment and installation
    • Automatic analysis and processing
  • Basic requirements of script

Script naming: Recommended".sh"ending
[root@server1 ~]# vim test.sh 
  1 #!/ Bin / bash < -- the first line of the script, magic characters, is used to specify the script bash, not the comment information
  2 
  3 # Name:test. SH < -- note, which describes the basic information of the script. It is recommended to write it out for easy reading
  4 # Desc: print 'hello linux'
  5 # Path:/root
  6 # Usage:./test.sh
  7 # Update:2021-15-07
  8 
  9 #Commands < -- specific commands to achieve specific functions
 10 echo 'hello linux'
 11 date +%F

Script execution method

Standard implementation

Recommended, common methods

Add execution permission to the script
[root@server1 ~]# chmod +x test.sh 
[root@server1 ~]# ls
anaconda-ks.cfg  test.sh(green)

Execute script
[root@server1 ~]# /root/test. SH < -- absolute path
hello linux
2021-09-05
[root@server1 ~]# ./ test. SH < -- relative path
hello linux
2021-09-05

Executing scripts using bash

The script is not required to have execution permission. This method is often used for troubleshooting

[root@server1 ~]# bash test.sh 
hello linux
2021-09-05
[root@server1 ~]# bash -x  test. SH < -- display execution process
+ echo 'hello linux'
hello linux
+ date +%F
2021-09-05
[root@server1 ~]# bash -n  test. SH < -- check the syntax of the shell script. No output indicates that the syntax is correct

Other methods to execute scripts

Only for writing configuration files

[root@server1 ~]# source test.sh 
hello linux
2021-09-05
[root@server1 ~]# . test.sh
hello linux
2021-09-05

variable

classification

Local variable (temporary)

The current user-defined variable is only valid for the current process, but not for other processes and child processes of the current process.

[root@server1 ~]# a=hello
[root@server1 ~]# echo $a
hello
[root@server1 ~]# ps
   PID TTY          TIME CMD
  8481 pts/0    00:00:00 bash
  8585 pts/0    00:00:00 ps
[root@server1 ~]# /bin/bash
[root@server1 ~]# ps
   PID TTY          TIME CMD
  8481 pts/0    00:00:00 bash #bash
  8601 pts/0    00:00:00 bash #bash subprocess
  8614 pts/0    00:00:00 ps
[root@server1 ~]# echo $a
 Invalid local variable
[root@server1 ~]# 

environment variable

The current process is valid and can be called by child processes

[root@server1 ~]# A=hello
[root@server1 ~]# echo $A
hello

env View environment variables
[root@server1 ~]# env |grep '^A'

Temporarily add local variables to environment variables
[root@server1 ~]# export A
[root@server1 ~]# env |grep '^A'
A=hello

Permanently add environment variables
[root@server1 ~]# echo 'export A=hello' >> /etc/profile
[root@server1 ~]# tail -1 /etc/profile
export A=hello

global variable

All users and programs can call

Important documents

  • ~/. bashrc: stores the bash information of the current user, such as user-defined alias, umask value, function, etc
  • ~/. bash_profile: stores the environment variables of the current user
  • /etc/bashrc: stores global bash information
  • /etc/profile: stores global environment variables

/etc/profile–> ~/. bash_ profile–> ~/. bashrc -->/etc/bashrc -->~/. bash_ Logout (the last file read before exiting the shell)

System variable

bash built-in variable with fixed meaning

$? The result of the execution of the previous command
	0,Normal exit
	127,Command not found
	126,insufficient privilege
	1&2,Indicates that there is no file or directory
[root@server1 ~]# ls
anaconda-ks.cfg
[root@server1 ~]# echo $?
0
[root@server1 ~]# ifconfig
-bash: ifconfig: Command not found
[root@server1 ~]# echo $?
127
[root@server1 ~]# vim test.sh
[root@server1 ~]# ./test.sh
-bash: ./test.sh: insufficient privilege
[root@server1 ~]# echo $?
126
[root@server1 ~]# ls aaa
ls: cannot access aaa: There is no such file or directory
[root@server1 ~]# echo $?
2

$$ Of the current process pid
[root@server1 ~]# ps
   PID TTY          TIME CMD
  8478 pts/0    00:00:00 bash
 11599 pts/0    00:00:00 ps
[root@server1 ~]# echo $$
8478
[root@server1 ~]# kill -9 `echo $$`
Connection closing...Socket close.
Connection closed by foreign host.
Disconnected from remote host(192.168.226.10:22) at 21:22:38.
Type `help' to learn how to use Xshell prompt.
[D:\~]$ 

$! Of the last process running in the background pid
[root@server1 ~]# sleep 1000 &
[1] 11631
[root@server1 ~]# sleep 2000 &
[2] 11632
[root@server1 ~]# jobs
[1]-  In operation               sleep 1000 &
[2]+  In operation               sleep 2000 &
[root@server1 ~]# echo $!
11632

!$ Call the last parameter in the last command history. If there is no parameter, call the command itself
[root@server1 ~]# vim /etc/sysconfig/network-scripts/ifcfg-ens33 
[root@server1 ~]# cat !$
cat /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE="Ethernet"
PROXY_METHOD="none"
BROWSER_ONLY="no"
BOOTPROTO="static"
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_FAILURE_FATAL="no"
IPV6_ADDR_GEN_MODE="stable-privacy"
NAME="ens33"
UUID="79065771-0af6-41b9-9112-1dd5b373f8ed"
DEVICE="ens33"
ONBOOT="yes"
IPADDR=192.168.226.10
GATEWAY=192.168.226.2
NETMASK=255.255.255.0
DNS1=114.114.114.114

!! Call the last historical command
[root@server1 ~]# !!
cat /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE="Ethernet"
PROXY_METHOD="none"
BROWSER_ONLY="no"
BOOTPROTO="static"
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_FAILURE_FATAL="no"
IPV6_ADDR_GEN_MODE="stable-privacy"
NAME="ens33"
UUID="79065771-0af6-41b9-9112-1dd5b373f8ed"
DEVICE="ens33"
ONBOOT="yes"
IPADDR=192.168.226.10
GATEWAY=192.168.226.2
NETMASK=255.255.255.0
DNS1=114.114.114.114

$# Number of script access parameters
$* All parameters behind the script are separated by spaces. All parameters are a whole
$@ All parameters behind the script are output, and the parameters are independent of each other
$0 Current program
$1-9 Position parameter variables, $1 Represents the first parameter passed into the script
${10}-{n} Position parameter variable,{}To define the scope
[root@server1 ~]# vim 1.sh
  1 #!/bin/bash
  2 
  3 #Desc = test system variable
  4 
  5 echo "\$# = $#"
  6 echo "\$* = $*"
  7 echo "\$@ = $@"
  8 echo "\$0 = $0"
  9 echo "\$1 = $1"
 10 echo "\$2 = $2"
 11 echo "\$3 = $3"
 12 echo "\$10 = ${10}"
[root@server1 ~]# chmod +x 1.sh 
[root@server1 ~]# ./1.sh
$# = 0
$* = 
$@ = 
$0 = ./1.sh
$1 = 
$2 = 
$3 = 
$10 = 
[root@server1 ~]# ./1.sh a b c
$# = 3
$* = a b c
$@ = a b c
$0 = ./1.sh
$1 = a
$2 = b
$3 = c
$10 =
[root@server1 ~]# ./1.sh 1 2 3 4 5 6 7 8 9 10
$# = 10
$* = 1 2 3 4 5 6 7 8 9 10
$@ = 1 2 3 4 5 6 7 8 9 10
$0 = ./1.sh
$1 = 1
$2 = 2
$3 = 3
$10 = 10
System variablemeaningremarks
$?The result of the execution of the previous command0, normal exit
$$pid of the current process
$!pid of the last process running in the background
!$Call the last parameter in the last command historyWithout parameters, the command itself is called
!!Call the last historical command
$#Number of script access parameters
$*All parameters after the scriptAll parameters as a whole
$@All parameters after the scriptThe parameters are independent of each other
$0Current program
$1-9Position parameter variable$1 represents the first parameter passed into the script
${10}-{n}Position parameter variable{} to define the scope

Define variables

Applicable scenarios:

  • A content is used multiple times and appears repeatedly in the code
  • Define the result of command execution as a variable, and then call the variable directly if you want to use the command result

Define variable rules

Variable name = variable value
There must be no spaces on either side of the equal sign
 Case sensitive
 Variable names cannot begin with numbers or special characters
 When the variable value changes, it is overwritten

[root@server1 ~]# A=hello
[root@server1 ~]# B='hello linux'
[root@server1 ~]# C=`date +%F`
Get variable
[root@server1 ~]# echo $A
hello
[root@server1 ~]# echo ${#A} #Get variable length
5
[root@server1 ~]# echo ${B}
hello linux
[root@server1 ~]# echo ${B:0:5}
hello
[root@server1 ~]# echo ${B:6:11}
linux
[root@server1 ~]# echo $C
2021-08-21

Delete variable
[root@server1 ~]# unset A
[root@server1 ~]# echo $A

[root@server1 ~]#
declare has type variables
Option description
-i Treat variables as integers 
-r readonly Variables are read-only and cannot be deleted or overwritten
-x Export to environment
-a Specify as index array (normal array); view normal array
-A Specify as associative array; View associative arrays

[root@server1 ~]# declare -x D=hi
[root@server1 ~]# env |grep '^D'
D=hi
read interaction
Option Description:
-p Prompt information
-n Specifies the maximum number of characters for the variable value
-s Do not display   
-t Specify timeout

[root@server1 ~]# read -p "please enter your name:" name
 Please enter your name:jack   

[root@server1 ~]# echo $name
jack
[root@server1 ~]# read -s -p "please enter your password:" passwd
 Please enter your password:[root@server1 ~]#

[root@server1 ~]# echo $passwd
1
[root@server1 ~]# read A B
aaa bbb
[root@server1 ~]# echo $A
aaa
[root@server1 ~]# echo $B
bbb

[root@server1 ~]# cat test.txt 
user01 123456
[root@server1 ~]# read user password < test.txt 
[root@server1 ~]# echo $user
user01
[root@server1 ~]# echo $password
123456
dirname&basename

dirname get variable pathname

basename get variable file name

[root@server1 ~]# A=/etc/sysconfig/network-scripts/ifcfg-ens33
[root@server1 ~]# dirname $A
/etc/sysconfig/network-scripts
[root@server1 ~]# basename $A
ifcfg-ens33
array
  • Normal array: only numbers can be used as array indexes
  • Associative array: you can use strings as array indexes
Define array
[root@server1 ~]# array[0]=v1
[root@server1 ~]# array[1]=v2
[root@server1 ~]# array[3]=v3
[root@server1 ~]# list=(v1 v2 v3 v4 v5 v6)

Get array
[root@server1 ~]# echo ${array[*]}
v1 v2 v3
[root@server1 ~]# echo ${list[*]}
v1 v2 v3 v4 v5 v6

View array index
[root@server1 ~]# declare -a |grep list
declare -a list='([0]="v1" [1]="v2" [2]="v3" [3]="v4" [4]="v5" [5]="v6")'
[root@server1 ~]# echo ${!list[@]}
0 1 2 3 4 5 6

section
[root@server1 ~]# echo ${list[*]} #Get all
v1 v2 v3 v4 v5 v6
[root@server1 ~]# echo ${list[@]} #Get all, ditto
v1 v2 v3 v4 v5 v6
[root@server1 ~]# echo ${list[1]} #Get by index
v2
[root@server1 ~]# echo ${list[*]:1:3} #Get part
v2 v3 v4
[root@server1 ~]# list[5]=value6 #modify
[root@server1 ~]# echo ${list[*]}
v1 v2 v3 v4 v5 value6
[root@server1 ~]# echo ${list[*]} #Add
v1 v2 v3 v4 v5 value6 v7
[root@server1 ~]# echo ${#list[*]} #Get the number of elements
7
-------------------------------------------------------------------
Define associative arrays
[root@server1 ~]# declare -A asso_array #Declare it as an associative array
[root@server1 ~]# asso_array[one]=v1
[root@server1 ~]# asso_array[two]=v2
[root@server1 ~]# asso_array[three]=v3

[root@server1 ~]# declare -A digi_array
[root@server1 ~]# digi_array=([aaa]=1 [bbb]=2 [ccc]=3)

Get associative array
[root@server1 ~]# echo ${asso_array[*]} #Get all
v2 v3 v1 #Associative arrays are unordered
[root@server1 ~]# echo ${digi_array[*]}
2 3 1
[root@server1 ~]# echo ${asso_array[one]} #Get by index
v1
[root@server1 ~]# echo ${#asso_array[@]} #Get the number of elements
3

View array index
[root@server1 ~]# declare -A |grep digi_array
declare -A digi_array='([bbb]="2" [ccc]="3" [aaa]="1" )'
[root@server1 ~]# echo ${!digi_array[@]}
bbb ccc aaa

Topics: Linux Operation & Maintenance shell