Shell script introduction


Shell script introduction

Shell brief introduction

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

User classification
$   It represents ordinary users
#   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 address #, and use Bang to become!
  • /Bin / bash indicates the location of bash interpreter commands. Of course, other interpreters can also be used
  • The Linux kernel will automatically read the first line and notice #/ Bin / bash, run / bin / bash to execute the script
Operation mode

Use the script as a command line argument to bash


Grant script execution permission and 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

Use rules

By default, echo adds a line break after each call
When using echo without quotation marks, semicolons cannot be used in the text to be displayed;, Because semicolons are used as command delimiters
When using double quotation marks, you need to escape characters when encountering special characters, but not in single quotation marks
Variable substitution is not valid in single quotes, such as ${username}

Escape character

a   Sound a warning tone
b   Delete previous character
c   No line breaks at the end
f   Line breaks, but the cursor remains in its original position
n   Wrap a 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   Same as f
 Insert character
nnn   Inserts 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
You can use the - e option to escape line breaks in echo

Print color output

Text flashing

0   Close all properties
one   Set high brightness (BOLD)
two   desalination
three   Italics
four   Underline
five   twinkle
seven   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...

Printf command usage rules

By default, printf does not automatically add line breaks like echo, which must be added manually

Format substitution

%s   character string
%c   ASCII   character
%d   Decimal integer
%f   Floating point number

Alignment format

-Align left
If not specified, the default is right alignment
You can add a number to indicate the width after aligning the symbols
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 essential 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 or not you use quotation marks when assigning a variable, the value will be 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
Just for the process
cat /proc/$PID/environ
By default, they are separated from each other by 0, which can be converted using the TR command
Use variables

Define variables


Use variables

echo $var
echo ${var}
Add path variable path
The path variable is usually defined in / etc / envitonment or / etc / profile or ~ /. Bashrc
export PATH="$PATH:/home/escape/bin"
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
Adding environment variables using functions

Add the following functions to ~ /. Bashrc

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

usage method

prepend PATH /opt/myapp/bin

Improvement scheme

prepend() { [ -d $2 ] && eval $1="$2${$1+':'$$1}" && export $1; }
#Use the expression ':' $$1 when $1 is not empty
#$$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)

Perform mathematical operations

In Bash shell environment, let, (()) and [] can be used to perform basic arithmetic operations, and expr and BC can be used for 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 square   echo   "10^10"  |  bc

Script judgment condition

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

Logical judgment
!   Logical non
-a   Logical and
-o   Logical or
Sentence judgment

interpretative statement

[-e   file]  # If   file   True if the file exists
[-d   file]  # If   file   True if it exists and is a directory
[-f   file]  # If   file   True if it exists and is an ordinary file
[-b   file]  # If   file   True if a special file exists and is a block
[-s   file]  # If   file   Exists and size is not   0   Is true
[-c   file]  # If   file   If it exists and is a word special file, it is true
[-h   file]  # If   file   True if there is a symbolic connection
[-p   file]  # If   file   The pipeline is true if it exists and is a name
[-r   file]  # If   file   True if it exists and is readable
[-w   file]  # If   file   True if it exists and is writable
[-x   file]  # If   file   True if it exists and is executable
[-L   file]  # If   file   True if there is a symbolic connection
[-S   file]  # If   file   True if a socket exists
[-O   file]  # If   file   Exists and is a valid user   ID   Is true
[-G   file]  # If   file   True if it exists and belongs to a valid user group
[-t   FD]    # If file descriptor   FD   True if open and pointing to a terminal
[-u   file]  # If   file   Exists and is set   Suid (with   chmod   u+s   Set) is true
[-g   file]  # If   file   Exists and has been set   Sgid (for   chmod   g+s   Set) is true
[-k   file]  # If   file   The adhesive bit exists and has been set (with   chmod   a+t   Set) is true
Conditional expression

interpretative statement

[string]      # string   The length of is non-zero   non-zero   Is true
[-n   string]   # string   The length of is non-zero   non-zero   Is true
[-z   string]    # string   If the length of is zero, it is true
[sting1==string2]  # If   two   True if two strings are the same
[string1!=string2]  # If   two   True if two strings are not equal
[string1  – eq   string2]  # Equal to true
[string1  - ne   string2]  # Not equal to true
[string1  - le   string2]  # Less than is true
[string1  – gt   string2]  # Greater than true
[string1  – ge   string2]  # Greater than or equal to true
[file1  – nt   file2]      # If   file1   than   file2   New or   file1   Exist and   file2   True if it does not exist
[file1  – ot   file2]      # If   file1   than   file2   Be old or   file2   Exist and   file1   True if it does not exist
[file1  – ef   file2]      # If   file1   and   file2   True if pointing to the same device and node number

Author: Escape
Article link:…

Shell script introduction