Shell script strategy


Shell script strategy

Shell brief introduction

Bash is adopted in the whole series of blogs, which is the default shell environment of most of the current gun / Linux systems, so most cases and discussions are based on this assumption.

User classification
$represents the average user
#Represents the administrator user root
  • Shell scripts are usually text files starting with shebang, such as #! / bin / bash
  • In UNIX jargon, use sharp or hash to call #, use Bang to become!
  • /Bin / bash indicates the location of the bash interpreter command. Of course, other interpreters can also be used
  • The Linux kernel will automatically read the first line and notice #! / bin / bash, and run / bin / bash to execute the script
Operation mode

Using script as command line parameter of Bash


Grant the script execution permission to become an executable file

  • Relative path
chmod a+x
  • Absolute path
chmod a+x

Command terminal printing

The terminal is an interactive tool, through which users can interact with the shell environment. Printing is the most basic task.

Echo command

Rules of use

By default, echo adds a newline character after each call
When you use echo without quotation marks, you cannot use a semicolon in the text you want to display; because the semicolon is used as a command delimiter
When using double quotation marks, escape characters are needed when special characters are encountered, but not in single quotation marks
Variable substitution is not valid in single quotation marks, such as ${username}

Escape character

A) sound a warning
Delete the previous character
c   No line feed at the end
F ﹣ wrap the line, but the cursor still stays in the original position
N ﹣ wrap the line and move the cursor to the beginning of the line
R ﹣ move the cursor to the beginning of the line without wrapping
t   Insert tab
V is the same as f
 Insert character
nnn   Insert the ASCII character represented by NNN (octal)

Common options

You can use direct output command results
You can use the - N option to ignore line breaks at the end
The - e option can be used to escape line breaks in echo

Print color output

Words flash

0 close all properties
1. Set high brightness (BOLD)
2. Desalination
three   Italics
4. Underline
5. Flicker
7. Reverse display
eight   Blanking

Color of words

Reset = 0, black = 30, red = 31, green = 32, yellow = 33, blue = 34, magenta = 35, cyan = 36, white = 37

background color

Reset = 0, black = 40, red = 41, green = 42, yellow = 43, blue = 44, magenta = 45, cyan = 46, white = 47

Example demonstration

[[email protected]] $ echo -e "e[1;31mWord is red e[0m"
Word is red
[[email protected]] $ echo -e "e[1;42mthe background is green e[0m"
the background is green
[[email protected]] $ echo -e "e[1;42;31mWord is red, the background is green e[0m"
Word is red, the background is green
[[email protected]] $ echo -e "e[5;37;31mMySQL Server Stop...e[0m"
MySQL Server Stop...
[[email protected]] $ echo -e "e[4;37;31mMySQL Server Stop...e[0m"
MySQL Server Stop...

Rules for using printf command

By default, printf does not automatically add line breaks as echo does, and must be added manually

Format replacer

%S ﹣ string
%c  ASCII  character
%D decimal integer
%F floating point number

Alignment format

-Align left
Not specified, right alignment by default
You can add a number after the alignment symbol to indicate the width
For floating-point numbers, you can use other parameters to trade off the decimal part, such as% -4.2f

Example demonstration

[[email protected]] $ printf "%-5s %-10s %-4.2fn" 1 escape 100.123
1   escape   100.12

Variables and environment variables

Variable is an indispensable part of any programming language, which is used to store all kinds of data.

  • In Bash, the value of each variable is a string
  • Whether you use quotation marks or not when you assign a value to a variable, the value is stored as a string
  • Environment variables are variables used by shell environment and operating system environment to store some special values
View environment variables
All terminal related
Env command
It's just about the process
cat /proc/$PID/environ
By default, they are divided by 0 before each other, and can be converted by using the TR command
Using variables

Defining variables


Using variables

echo $var
echo ${var}
Add path variable path
The path variable is usually defined in / etc / enclosure or / etc / profile or ~ /. Bashrc
export PATH="$PATH:/home/escape/bin"
The use of variables

Get string length


Identify the shell currently in use

echo $SHELL
echo $0

Check whether it is a super user

[ $UID -ne 0 ]

Modify bash prompt

echo $PS1
PS1='${debian_chroot:+($debian_chroot)}[email protected]:w$'
You can use specific escape characters like E [1; 31] to set the color Prompt string
Using functions to add environment variables

Add the following function to ~ /. Bashrc

prepend() { [ -d "$2" ] && eval $1="$2':'$$1" && export $1; }
  • Determine whether the directory specified by the second parameter exists
  • Set the variable value pointed by the first parameter to the value of the second parameter plus $1
  • Set to environment variable

usage method

prepend PATH /opt/myapp/bin

Improvement plan

prepend() { [ -d $2 ] && eval $1="$2${$1+':'$$1}" && export $1; }
#Where $1 is not empty, the expression ':' $$1 is used
#$$1 represents the actual value of the first parameter
Example demonstration
[[email protected]] $ pgrep gedit
[[email protected]] $ cat /proc/12501/environ
[[email protected]] $ cat /proc/12501/environ | tr '0' 'n'
[[email protected]] $ count=5
[[email protected]] $ fruit=apple
[[email protected]] $ echo "We hava $count ${fruit}(s)"
We have 5 apple(s)
[[email protected]] $ echo '$var' will print $var
$var will print $var
[[email protected]] $ echo $PATH
[[email protected]] $ export PATH="$PATH:/home/escape/bin"
[[email protected]] $ PATH="$PATH:/home/escape/bin"
[[email protected]] $ export PATH
[[email protected]] $ echo $PS1
${ret_status} %{$fg[cyan]%}%c%{$reset_color%} $(git_prompt_info)

Do mathematical operations

In Bash shell environment, let, (()) and [] can be used to perform basic arithmetic operations, and expr and BC can be used to perform advanced operations

Basic arithmetic
let result=num1+num2
let num++
let num--
let num+=5
let num-=5
result=$[ num1+num2 ]
result=$[ $num+5 ]
Advanced arithmetic
result=expr 3+4
result=$(expr $num+5)
Common usage: echo "4 * 0.56" | BC
Set decimal precision  echo "scale=2; 3/8" | bc
Decimal to binary  echo "obase=2; $num" | bc
Binary to decimal | echo "obase = 10; IBASE = 2; $num" | BC
Square root | echo "sqrt (100)" | BC
Calculate the square of echo "10 ^ 10" | BC

Script judgment condition

To write a good shell script, you need to be familiar with the following judgment conditions and rules

Logical judgment
! logical not
-A ﹣ logical and
-o   Logical or
Sentence judgment

interpretative statement

[- e file] # true if file exists
[- D file] # true if file exists and is a directory
[- f file] # true if file exists and is a normal file
[- B file] # true if file exists and is a block special file
[- s file] # true if file exists and size is not 0
[- C file] # true if file exists and is a special word file
[- H file] # true if file exists and is a symbolic connection
[- P file] # true if file exists and is a named pipe
[- R file] # true if file exists and is readable
[- W file] # true if file exists and is writable
[- x file] # true if file exists and is executable
[- L file] # true if file exists and is a symbolic connection
[- s file] # true if file exists and is a socket
[-O  file] # If  file  Existing and valid user  ID  It is true
[-G  file] # If  file  True if there is a valid user group
[-t  FD]   # If the file descriptor  FD  Open and point to a terminal is true
[- U file] # true if "file" exists and "suid" is set (set with "CHMOD U + s")
[- G file] # true if 'file' exists and 'sgid' has been set (set with 'Chmod' G + s')
[- K file] # true if "file" exists and the glue bit has been set (set with "Chmod a + T")
Conditional expression

interpretative statement

If the length of [string] # string is non-zero, then it is true
The length of [- N? String] # string is non-zero, then it is true
If the length of [- Z string] # string is zero, it is true
[string1 = = string2] # true if two strings are the same
[string1! = string2] # true if two strings are not equal
[string1 – EQ? String2] # is true
[string1 - Ne? String2] # is not true
[string1 - Le? String2] # less than true
[string1 – GT] string2] # greater than is true
[string1   –ge  string2] # Greater than or equal to true
[file1 – NT File2] # true if 'file1' is newer than 'File2', or 'file1' exists and 'File2' does not exist
[file1 – ot File2] # true if 'file1' is older than 'File2' or 'File2' exists and 'file1' does not exist
[file1 – EF File2] # true if file1 and File2 point to the same device and node number

Author: Escape
Article link:…

Shell script strategy