Shell Programming Specification Variable Details (shell programming specifications in Linux, how scripts are executed, pipe symbols and redirections, shell variable types)

Preface

Shell is a program written in C that serves as a bridge for users to use Linux. Shell is both a command language and a programming language.
_The execution of Linux commands must depend on the shell command interpreter. Shell is actually a special program that runs in the Linux operating system. It is located between the kernel of the operating system and the user. It receives commands from the user and interprets them. The operation that needs to be performed is passed to the system kernel for execution. The shell acts as a "translator" between the user and the kernel. When a user logs on to a Linux system, a shell program is automatically loaded to provide the user with an operating system on which to enter commands.

One: An overview of shell scripts

1.1: The concept of shell Scripting

  • Save the commands to be executed in order to a text file
  • Give this file executable permissions to run + execute permissions for one x
  • Various shell control statements can be combined to complete more complex operations

1.2: shell script application scenario

  • Repeated operation
  • Batch Transaction
  • Automated Operations and Maintenance Management
  • Server running status monitoring
  • Timed Task Execution
  • ......
    What the shell does--command interpreter, "translator"

1.3: User's login shell

  • The shell program used by default after login, typically / bin/bash
  • Different shell s have different internal commands, running environments, and so on
[root@server1 ~]# cat /etc/shells 
/bin/sh
/bin/bash
/sbin/nologin
/usr/bin/sh
/usr/bin/bash
/usr/sbin/nologin
/bin/tcsh
/bin/csh

1.31:type command - Displays the specified command type

[root@shuai opt]# type cd
cd yes shell Embedded
[root@shuai opt]# type mkdir
mkdir yes /usr/bin/mkdir
[root@shuai opt]# type bash
bash yes /usr/bin/bash
[root@shuai opt]# type which
which yes `alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde' Alias of

1.4: Write the first shell script

1.41: Scripting code

  • Using vi text editor
  • One Linux command per line, written in sequence for execution
  • The script is suffixed with. sh
vim cendy.sh
#!/bin/bash           #shell script fixed format
cd /boot              #Switch to boot directory
pwd                   #View current location
ls -lh vml*           #See all files at the beginning of vml
:wq                   #ESC Switch to Command Mode Save Exit
[root@server1 test]# ls -lh
 Total usage 4.0K
-rwxr-xr-x. 1 root root 38 9 January 18 14:10 cendy.sh

1.4.2 Grant executable rights

[root@server1 test]# chmod +x cendy.sh

1.5: Execute script file

  • Method 1: Script file path (absolute path vs. relative path)
[root@server1 test]# ls -lh
 Total usage 8.0K
-rwxr-xr-x. 1 root root 38 9 January 18 14:10 cendy.sh
-rw-r--r--. 1 root root 25 9 January 18 14:25 jerry         #No Execution Rights
[root@server1 test]# ./jerry.sh
-bash: ./jerry.sh: insufficient privilege 
[root@server1 test]# ./cendy.sh 
/boot
-rwxr-xr-x. 1 root root 5.7M 8 February 2617:42 vmlinuz-0-rescue-34c5caefc7194359afe5202e8cdfd9fe
-rwxr-xr-x. 1 root root 5.7M 8 February 23, 2017 vmlinuz-3.10.0-693.el7.x86_64
  • Method 2: sh script file path
[root@server1 test]# sh jerry.sh 
/boot
-rwxr-xr-x. 1 root root 5.7M 8 February 2617:42 vmlinuz-0-rescue-34c5caefc7194359afe5202e8cdfd9fe
-rwxr-xr-x. 1 root root 5.7M 8 February 23, 2017 vmlinuz-3.10.0-693.el7.x86_64

2: Redirection and Pipeline Operation

2.1: Interactive Hardware Device 0 1 2

  • Standard Input: Receive user input data from the device
  • Standard Output: Output data to the user through the device
  • Standard error: Error information is reported by the device
type Device Files File Description Default device
Standard Input /dev/stdin 0 keyboard
Standard Output/dev/stdout 1 Monitor
Standard error output /dev/stder 2 Monitor

2.2: Redirection operation

type Operator purpose
redirect input < Read data from the specified file instead of typing it from the keyboard
redirect output > Save output to specified file (overwrite)
redirect output >> Append output to specified file
Standard error output 2 > Save error information to the specified file (overwrite)
Standard error output 2>> Append error information to specified file
Mixed Output & > Save the contents of Standard Output and Standard Errors in the same file

2.3: Pipeline operation symbol'|'

  • Output the left command as the processing object for the right command
[root@server1 test]# grep "bash$" /etc/passwd        #View logins ending with bash
root:x:0:0:root:/root:/bin/bash
amandabackup:x:33:6:Amanda user:/var/lib/amanda:/bin/bash
qy:x:1000:1000:qyf:/home/qyf:/bin/bash
#Separated by colons, output 1,7 Fields    ##If not - F is the indicator symbol and the space
[root@server1 test]# grep "bash$" /etc/passwd | awk -F: '{print $1.$7}'
root/bin/bash
amandabackup/bin/bash
qyf/bin/bash

awk is one of the regular expressions

In most cases  
grep: Filter keywords  grep egrep 
sed Second child reads by line
awk Third Three Read Data Column by Column
sed:  Read by line
awk: Read data by column
$1,$7:Location variable
[root@shuai opt]# df -Th
 file system                type      Capacity used Available Used% mount point
/dev/mapper/centos-root xfs        50G  5.0G   46G   10% /
devtmpfs                devtmpfs  3.6G     0  3.6G    0% /dev
tmpfs                   tmpfs     3.6G     0  3.6G    0% /dev/shm
tmpfs                   tmpfs     3.6G   13M  3.6G    1% /run
tmpfs                   tmpfs     3.6G     0  3.6G    0% /sys/fs/cgroup
/dev/sda1               xfs      1014M  179M  836M   18% /boot
/dev/mapper/centos-home xfs       242G   33M  242G    1% /home
tmpfs                   tmpfs     726M  4.0K  726M    1% /run/user/42
tmpfs                   tmpfs     726M   48K  726M    1% /run/user/0
/dev/sr0                iso9660   4.3G  4.3G     0  100% /run/media/root/CentOS 7 x86_64

####Extract the first and sixth
[root@shuai opt]# df -Th | awk '{print $1,$6}'
File System Used%
/dev/mapper/centos-root 10%
devtmpfs 0%
tmpfs 0%
tmpfs 1%
tmpfs 0%
/dev/sda1 18%
/dev/mapper/centos-home 1%
tmpfs 1%
tmpfs 1%
/dev/sr0 100%
##Filter to/End Column 1 and Column 6
[root@shuai opt]# df -Th | grep "/$" | awk '{print $1,$6}'
/dev/mapper/centos-root 10%

3: shell script variables in detail

3.1: The role of variables, type variables: variables are the most common type of programming

A way to temporarily access data in memory

3.11: The Role of Variables

Providing specific parameters for flexible management of limux systems has two meanings
Variable name: Use a fixed name, defined by the system or user
Variable value: Ability to change according to user settings, system environment changes

3.12: Type of variable

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

3.2: Custom variables

3.21: Define a new variable and view its value

Define a new variable - Custom variable = echo
Variable names start with subtitles or underscores, case-sensitive, full capitalization recommended
Variable Format Variable Name=Variable Value
View the value of a variable
echo $variable name

3.22: Variable naming rules

Naming can only be done with letters, numbers, and underscores. The first character cannot start with a number'
No space in the middle. You can use a hanging line below-
Punctuation cannot be used
 Out of commission bash Keyword [Available help Command View Reserved Keyword)

VFDA=2
age=90 integer##This side=called assignment symbol
name='baisn'string
score=88.8 [single precision floating point 4 bytes] shuai=8.88 [double precision floating point 8 bytes]

[root@server1 test]# dd=20
[root@server1 test]# $dd=20
bash: 20=20: Command not found...
[root@server1 test]# echo $dd 20
20 20
[root@server1 test]# echo $dd 
20
[root@server1 test]# name=dd
[root@server1 test]# echo $name
cc
[root@server1 test]# echo $name dd
cc dd

3.23: Cancel variable unset

[root@server1 test]# name=aa
[root@server1 test]# echo $name 
aa
[root@server1 test]# unset name    #Cancel Variable
[root@server1 test]# echo $name 

#Output is empty

3.24: Use quotation marks when assigning values

  • Double Quotes
    Allow references to other variable values by symbols, that is, if they can represent strings, if they can represent strings, if they can represent strings, and if they can represent strings, if they can represent scalars.
  • Single quotation mark

Forbidden to refer to other variable values, is for ordinary characters, that is, treated as strings, variable symbol apostrophe is not recognized: command substitution, extract the output result variable after command execution = apostrophe equals variable=()

[root@server1 test]# siri=10
[root@server1 test]# echo $siri 
10
[root@server1 test]# siri2="50 $siri"
[root@server1 test]# echo $siri2
50 10
[root@server1 test]# siri=`ps aux | wc -l`
[root@server1 test]# echo $siri
204
[root@server1 test]# siri='ps aux | wc -l'
[root@server1 test]# echo $siri
ps aux | wc -l

3.25: Assign read to variables from keyboard input

[root@server1 test]# vim weather.txt
#!/bin/bash
read -p "Please enter today's weather:" weather
echo "Today's weather is: $weather"
#Command mode: wq save exit
[root@server1 test]# chmod +x weather.txt 
[root@server1 test]# ./weather.txt 

3.26: Set the scope of the variable export Settings are globally available

  1. Format 1: export variable name
  2. Format 2: export variable name = variable value
  3. The two formats can be mixed
    export can define a variable as a global variable so that it can be used either by switching bash environments or by switching users
[root@server1 test]# tom=shu
[root@server1 test]# echo $tom 
shu
[root@server1 test]# bash           #Setting up the bash environment
[root@server1 test]# echo $tom
#Output is empty
[root@server1 test]# exit           #Exit bash environment
exit
[root@server1 test]# echo $tom 
shu
[root@server1 test]# export tom     #Set as Global Variable
[root@server1 test]# bash
[root@server1 test]# echo $tom      #Reference to global variables
shu

3.27: Operational expr for integer variables

expr variable 1 operator variable 2 [operator variable 3].....
Common Operators

  1. Addition operation: +
  2. Subtraction operation: -
  3. Multiplication: * Multiplication must be accompanied by \ because * represents a wildcard symbol in shell languages
  4. Division operation: /
  5. Modulo (Remainder) operation:%
[root@server1 test]# expr 1 + 2
3
[root@server1 test]# expr 5 -  2
3
[root@server1 test]# expr 5 \*  2
10
[root@server1 test]# expr 2 / 2
1
[root@server1 test]# expr 5 %  2
1
[root@server1 test]# vim test1.sh
#!/bin/bash
read -p "A few hours of study the first day:" time1
read -p "The next day I studied for a few hours:" time2
time=`expr $time1 + $time2`
echo "The sum of two days of study is $time " 
[root@server1 test]# chmod +x test1.sh 
[root@server1 test]# ./test1.sh 
A few hours of study the first day:12
 The next day I studied for a few hours:12
 The sum of two days is 24  

Four: Special shell variables

4.1 Environment Variables

  • Pre-created by the system to set the user's working environment
  • Configuration file: /etc/profile, ~/. bash_prolile

4.2 Common environmental variables

  • PWD\,PATH
  • USER,SHELL,HOME
[root@server1 test]# echo $PATH 
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
[root@server1 test]# echo $PWD 
/root/test
[root@server1 test]# vim test2.sh
[root@server1 test]# sh test2.sh 40 20
 First value 40
 Second value 20
 The result of the subtraction operation is 20

4.3: Predefined variables

  1. $#: Number of location variables on the command line
  2. $*: Content of all location variables
  3. $?: The status returned after the last command execution, normal when the return status value is 0, and non-zero when execution exception or error
  4. $0: Currently executing process/program name
  5. Analysis script
[root@server1 test]# vim test3.sh
#!/bin/bash
t=b-`date +%s`.tgz                  #Set variable name, +%s for seconds since 1970
tar zcvf $t $* &> /dev/null       #Compress to/dev/null    
echo "executed $0 Scripts"
echo "Total Completion $#Backup of objects
echo "The specific contents include: $*"
[root@server1 test]# chmod +x test3.sh 
[root@server1 test]# ./test3.sh /etc/passwd /etc/shadow
 executed./test3.sh Scripts
 Backup of 2 objects completed
 The specific contents include:/etc/passwd /etc/shadow
#/dev/null:black hole
%Y Year
%m Represents the month
%d Representation Day
%H Represents an hour
%M Represents a minute
%S Represents seconds
%s Represents 100 since January 1, 1970:00:00 UTC Seconds so far, equivalent to time function
%w Represents the day of the week.

[root@server1 test]# date
2020 Sunday, 20 September 2002 22:04:22 CST
[root@server1 test]# date +%Y%D$%H:%M
202009/20/20$22:03
[root@server1 test]# date +%s      #Seconds since January 1, 1970
1600610688

Tags: Programming Linux Operation & Maintenance shell cloud computing

Posted by simonmlewis on Sun, 15 May 2022 20:50:07 +0300