Shell Programming - A Quick Start Guide to Scripting Languages with Weak Data Types

Table of contents

Linux Shell

type of data

variable type

operator

arithmetic operator

assignment operator

concatenation operator

comparison operator

relational operator

control structure

sequential structure

conditional branch structure

if conditional statement

case branch statement 

loop structure

for loop

while loop

until loop

break statement

continue statement

function

function definition 

Function name

function body

return value

parameter

function locality

Simple function example

function recursion

instance operation

array traversal operation

Nine nine multiplication table


Basically, every programming language can start from the five aspects of data types, variables, operators, control structures, and functions. If you master these contents initially, you can quickly get started as a junior programmer.

Linux Shell

Shell is a Linux command line interpreter, mainly used to execute operating system commands and scripts. The Linux Shell programming language is a command-line scripting language used to interact with the operating system kernel. It is an interpreted and weakly typed dynamic language.

type of data

bool, number, string, array

variable type

Environment variables, user variables, global variables, read-only variables

set let export readonly  env

operator

arithmetic operator

+ - * / %

assignment operator

=, there is no compound assignment like +=, -=, *=, /=

concatenation operator

+= , can only be used for concatenation of strings

comparison operator

==、!=

relational operator

-eq Checks whether two numbers are equal, equal returns true.
-ne Checks whether two numbers are not equal, and returns true if they are not equal.
-gt Check if the number on the left is greater than the number on the right, and if so, return true.
-lt Checks if the number on the left is less than the number on the right, and if so, returns true.
-ge Checks whether the number on the left is greater than or equal to the number on the right, and if so, returns true.
-le Checks whether the number on the left is less than or equal to the number on the right, and if so, returns true.

control structure

sequential structure

The sequence structure is the simplest algorithm structure, and the statements are executed sequentially from top to bottom, and it is composed of several processing steps executed in sequence.

Note: There can be multiple statements on the same line, as long as they are separated by a semicolon ";".

conditional branch structure

if conditional statement

Can be subdivided into if , if-else , if-elif-else multiple forms

hann@HannYang:~$ help -m if
NAME
    if - Execute commands based on conditional.

SYNOPSIS
    if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi

DESCRIPTION
    Execute commands based on conditional.

    The `if COMMANDS' list is executed.  If its exit status is zero, then the
    `then COMMANDS' list is executed.  Otherwise, each `elif COMMANDS' list is
    executed in turn, and if its exit status is zero, the corresponding
    `then COMMANDS' list is executed and the if command completes.  Otherwise,
    the `else COMMANDS' list is executed, if present.  The exit status of the
    entire construct is the exit status of the last command executed, or zero
    if no condition tested true.

    Exit Status:
    Returns the status of the last command executed.

......

case branch statement 

hann@HannYang:~$ help -m case
NAME
    case - Execute commands based on pattern matching.

SYNOPSIS
    case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac

DESCRIPTION
    Execute commands based on pattern matching.

    Selectively execute COMMANDS based upon WORD matching PATTERN.  The
    `|' is used to separate multiple patterns.

    Exit Status:
    Returns the status of the last command executed.

......

loop structure

for loop

hann@HannYang:~$ help -m for
NAME
    for - Execute commands for each member in a list.

SYNOPSIS
    for NAME [in WORDS ... ] ; do COMMANDS; done

DESCRIPTION
    Execute commands for each member in a list.

    The `for' loop executes a sequence of commands for each member in a
    list of items.  If `in WORDS ...;' is not present, then `in "$@"' is
    assumed.  For each element in WORDS, NAME is set to that element, and
    the COMMANDS are executed.

    Exit Status:
    Returns the status of the last command executed.

......

while loop

hann@HannYang:~$ help -m while
NAME
    while - Execute commands as long as a test succeeds.

SYNOPSIS
    while COMMANDS; do COMMANDS; done

DESCRIPTION
    Execute commands as long as a test succeeds.

    Expand and execute COMMANDS as long as the final command in the
    `while' COMMANDS has an exit status of zero.

    Exit Status:
    Returns the status of the last command executed.

......

until loop

hann@HannYang:~$ help -m until
NAME
    until - Execute commands as long as a test does not succeed.

SYNOPSIS
    until COMMANDS; do COMMANDS; done

DESCRIPTION
    Execute commands as long as a test does not succeed.

    Expand and execute COMMANDS as long as the final command in the
    `until' COMMANDS has an exit status which is not zero.

    Exit Status:
    Returns the status of the last command executed.

......

break statement

hann@HannYang:~$ help -m break
NAME
    break - Exit for, while, or until loops.

SYNOPSIS
    break [n]

DESCRIPTION
    Exit for, while, or until loops.

    Exit a FOR, WHILE or UNTIL loop.  If N is specified, break N enclosing
    loops.

    Exit Status:
    The exit status is 0 unless N is not greater than or equal to 1.

......

continue statement

hann@HannYang:~$ help -m continue
NAME
    continue - Resume for, while, or until loops.

SYNOPSIS
    continue [n]

DESCRIPTION
    Resume for, while, or until loops.

    Resumes the next iteration of the enclosing FOR, WHILE or UNTIL loop.
    If N is specified, resumes the Nth enclosing loop.

    Exit Status:
    The exit status is 0 unless N is not greater than or equal to 1.

......

the difference between the two 

break statement:

The break statement is used to exit the current loop. When the break is executed, it will immediately jump out of the current loop and execute the subsequent code.
In a multi-level nested loop, break will only jump out of the nearest level of loop.

continue statement:

The continue statement is used to end this loop, skip the remaining code in this loop, and directly enter the next loop.
In a multi-level nested loop, continue will only skip the nearest level of loop.

function

hann@HannYang:~$ help -m function
NAME
    function - Define shell function.

SYNOPSIS
    function name { COMMANDS ; } or name () { COMMANDS ; }

DESCRIPTION
    Define shell function.

    Create a shell function named NAME.  When invoked as a simple command,
    NAME runs COMMANDs in the calling shell's context.  When NAME is invoked,
    the arguments are passed to the function as $1...$n, and the function's
    name is in $FUNCNAME.

    Exit Status:
    Returns success unless NAME is readonly.

function definition 

Function name

Shell functions are declared with the keyword function, followed by the name of the function. After the declaration, use "function name [parameter]" to call the function. function is not required, you can also use the function name plus a pair of brackets name() { ... } to declare and define the function.

function body

The { Commands; } after the function name is the function body, which is the main body to realize the functions of the function.

return value

Shell functions can have a return value, and a return statement can be used to return a value. The return value ranges from 0 to 255, with 0 indicating success and a non-zero value indicating an error. If there is no return statement in the function, or the exit command is used to exit the function, the return value of the function is the return value of the exit command.

parameter

Shell functions can receive input values ​​through parameters. When a function is defined, an argument list can be specified within parentheses. Parameters can be used in the function body, or the number of parameters of the function can be obtained through the special variable $#, and all parameters can be obtained through the special variable $@.

function locality

The variables of the Shell function are local, that is, the variables defined inside the function are only visible inside the function, and will not affect the variables outside the function. If you want to use global variables, you need to define them outside the function.

Simple function example

hann@HannYang:~$ function add {
>     num1=$1
>     num2=$2
>     sum=$((num1 + num2))
>     echo "The sum of $num1 and $num2 is $sum."
> }
hann@HannYang:~$ add 10 20
The sum of 10 and 20 is 30.

 A function with fewer statements can be completed in one line, and the statements in the function body can be separated by a semicolon ";".

hann@HannYang:~$ function sub { num1=$1; num2=$2; sum=$((num1 - num2)); echo "The difference between $num1 and $num2 is $sum."; }
hann@HannYang:~$ sub 30 20
The difference between 30 and 20 is 10.

function recursion

Shell functions can call themselves recursively, which is useful when dealing with nested data structures or recursive algorithms. It should be noted that recursive calls may cause stack overflow or inefficiency, so you need to be cautious when using them.

Example: Factorial function

hann@HannYang:~$ factorial() {
>     if [ $1 -le 1 ]
>     then
>         echo 1
>     else
>         echo $(( $1 * $(factorial $(( $1 - 1 ))) ))
i
}>     fi
> }
hann@HannYang:~$ read -p "请输入一个整数:" num
请输入一个整数:6
hann@HannYang:~$ result=$(factorial $num)
hann@HannYang:~$ echo "$num 的阶乘为 $result"
6 的阶乘为 720

instance operation

array traversal operation

hann@HannYang:~$ for i in 1 2 3 4 5; do echo -n $i; done; echo
12345
hann@HannYang:~$ for i in {1..5}; do echo -n $i; done; echo
12345
hann@HannYang:~$ sum=0;for i in {1..100};do let sum+=i;done;echo $sum
5050
hann@HannYang:~$ for i in {1..5}{8..10}; do echo -n $i; done; echo
18191102829210383931048494105859510
hann@HannYang:~$ for i in {1..5}{8..10}; do echo -n $i" "; done; echo
18 19 110 28 29 210 38 39 310 48 49 410 58 59 510
hann@HannYang:~$ for i in {A..C}{a..d}; do echo -n $i" "; done; echo
Aa Ab Ac Ad Ba Bb Bc Bd Ca Cb Cc Cd

Nine nine multiplication table

hann@HannYang:~$ cat 99mul.sh

#!/bin/bash

for i in {1..9}
do
   for j in {1..9}
   do
     if [ $j -le $i ]
     then
        echo -n "$j*$i=$(($i*$j)) "
     fi
   done
   echo ""
done

hann@HannYang:~$ bash 99mul.sh

1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81

hann@HannYang:~$ cat 99mul.sh

#!/bin/bash

for i in {1..9}
do
   for j in {1..9}
   do
     if [ $j -le $i ]
     then
        printf "%d*%d=%2d " $j $i $(($i*$j))
     fi
   done
   echo ""
done

hann@HannYang:~$ bash 99mul.sh

1*1= 1
1*2= 2 2*2= 4
1*3= 3 2*3= 6 3*3= 9
1*4= 4 2*4= 8 3*4=12 4*4=16
1*5= 5 2*5=10 3*5=15 4*5=20 5*5=25
1*6= 6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7= 7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8= 8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9= 9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81

hann@HannYang:~$ cat 99mul.sh 

#!/bin/bash

for i in {1..9}
do
   for j in {1..9}
   do
     if [ $j -le $i ]
     then
        if [ $j -eq 1 ]
        then
            printf "%d*%d=%d " $j $i $(($i*$j))
        else
            printf "%d*%d=%2d " $j $i $(($i*$j))
        fi
     fi
   done
   echo ""
done

hann@HannYang:~$ bash 99mul.sh

1*1=1
1*2=2 2*2= 4
1*3=3 2*3= 6 3*3= 9
1*4=4 2*4= 8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81


This article briefly mentions the key points of getting started with the Linux Shell programming language, and then classifies each link in detail with examples.

Guess you like

Origin blog.csdn.net/boysoft2002/article/details/132253682