Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Shell appendix

May 23, 2021 Shell - An example of programming

Table of contents

Shell programming learning notes


This is the author's early Shell programming learning notes, including shell overview, shell variables, location parameters, special symbols, alias, various control statements, functions and other Shell programming knowledge.

To systematically learn Shell, you should look for more systematic materials, such as Shell Programming Paradigms and Bird Brother Learning Shell Scripts.

How shell scripts are executed

Example: Input redirects to Bash

$ bash < ex1

You can read into the program in ex1 and execute it

Example: Use the script name as an argument

The general forms are:

$ bash 脚本名 [参数]

For example:

$ bash ex2 /usr/meng /usr/zhang

The execution is the same as the one before, but the advantage of this approach is that it can be followed by parameters that pass parameter values to commands in the program, allowing a shell script to handle a variety of situations, just as function calls can pass the appropriate arguments based on specific problems.

Example: To . to execute

If you execute a shell script · the current shell ( in , ) you can use the following simple form:

$ · ex3[参数]

Example: Direct execution

Set the permissions of the shell script to executable, and then execute it directly at the prompt.

How to do this:

$ chmod a+x ex4
$ ./ex4

This requirement indicates at the beginning of the shell script the specific shell that executed the script, /bin/bash


The execution principle of the shell

Shell receives user-entered commands (script names) and analyzes them. I f the file is marked as executable, but not a compiled program, shell considers it a shell script. T he shell reads what is in it and interprets the execution. Therefore, from the user's point of view, shell scripts are executed in a similar way to executing a typical executable file.

As a result, user-developed shell scripts can reside under the directory of the command search path /bin /usr/bin and be used like normal commands. I n this way, you develop your own new commands. This is convenient if you plan to use the scripted shell script over and over again.

Variable assignment

You can assign the execution result of a command to a variable. There are two forms of command substitution: one is to refer to a command in reverse quotes, which is generally in the form of 命令表

Example: Get the current working directory and store it in a variable

For example, store the full path name of the current working directory in the variable dir and enter the following command line:

$ dir=`pwd`

Another form is$ $(命令表) The command line above can also be rewritten to read:

$ dir=$(pwd)


Bash only one-dimensional arrays and does not limit the size of the arrays. S imilar to the C language, the underling of an array element is numbered from 0. G ets the elements in the array to take advantage of the underseed. T he subse cursor can be an integer or arithmetic expression whose value should be greater than or equal to 0. Users can assign values to array variables using assignment statements.

Example: Assign an assignment to an array element

The general form of assigning an assignment to an array element is: array name 数组名[下标]=值 example:

$ city[0]=Beijing
$ city[1]=Shanghai
$ city[2]=Tianjin

You can also explicitly declare an array with the declare command, typically in the form of:

$ declare -a 数组名

Example: Access an array element

The general format for reading the values of array elements is: ${数组名[下标]} for example:

$ echo ${city[0]}

Example: Array combination assignment

Individual elements of an array can be assigned one element at a time, or they can be combined. The general form of defining an array and assigning it an initial value is:

数组名=(值1 值2 ... 值n)

Where the values are separated by spaces. For example:

$ A=(this is an example of shell script)
$ echo ${A[0]} ${A[2]} ${A[3]} ${A[6]}
this an example script
$ echo ${A[8]}

Because there are 7 initial values in the value A number of elements in A is also 7. A[8] array A is considered a new element whose value is an empty string because it is not assigned in advance.

If the undersequencation of the array element is not given, the array name represents the array element labeled 0, city which is city[0]

Example: List everything in the array

By * @ s to make the underseed, all elements in the array are replaced.

$ echo ${A[*]}
this is an example of shell script

Example: Get the number of array elements

$ echo ${#A[*]}

The argument is passed

If you want to write a shell to find the two numbers of the same, how can you achieve it? To describe the use of parameter passing, write a script like this:

$ cat > add
let sum=$1+$2
echo $sum

After saving, do this:

$ chmod a+x ./add
$ ./add 5 10

You can see that 5 and 10 are $1 $2 which is the shell's own preset order of parameters, but you can actually define the variables and pass them in.

For example, modifying the above script to get:

let sum=$X+$Y
echo $sum

Do it again:

$ X=5 Y=10 ./add

As you can see, you can get the right results as well.

Set the environment variable

Export an environment variable:

$ export opid=True

This way, if you want to log in and take effect, you can add it directly to /etc/profile ~/.bashrc

The keyboard reads the variable value

You read variable values, for example, to wait for the user to enter a value and display it:

$ read -p "请输入一个值 : "  input ; echo "你输入了一个值为 :" $input
请输入一个值 : 21500
你输入了一个值为 : 21500

Sets the read-only properties of the variable

There are some important shell variables that should not be modified after being assigned, so you can set readonly

$ oracle_home=/usr/oracle7/bin
$ readonly oracle_home

Conditional test command test

test 表达式 Expression If the expression is true, it returns true, otherwise, it returns false.

Example: Numerical comparison

The common comparison characters when comparing values are given first:

-eg =;-ne !=;-gt >;-ge >=;-lt <;-le <=

$ test var1 -gt var2

Example: Test file properties

Readable, writeable, executable, whether the file is normal, whether the directory corresponds to:

-r; -w; -x; -f; -d

$ test -r filename

Example: Character pass properties and comparisons

The length of the string is zero: -z non-zero: -n such as:

$ test -z s1

If the s1 length is zero, return true.

Example: String comparison

Equal "s1"="s2" is "s1"!="s2"

There is also a method of comparing strings (which can be compared in dictionary order):

$ if [[ 'abcde' < 'abcdf' ]]; then  echo "yeah,果然是诶"; fi

Integer arithmetic or relationship operation expr

The operations that can be performed with this command are:

+ - * / % operations: := ! < <= > >=

Such as:

$ i=5;expr $i+5

In addition, bc is a command-line calculator that can perform some arithmetic calculations.

Controls the execution of process commands

Example: Conditional branch command if

if the first argument is a normal file name, the file is pedded;

if test -f $1
    pr $1>/dev/lp0
    test-d $1
    (cd $1;pr *>/dev/lp0)
    echo $1 is neither a file nor a directory

Example: Case command example

case command is a pattern-matched multi-branch command, and the next set of commands will be executed based on the user's keyboard input.

while$reply!="y" ] && [ $reply!="Y" ]                         #下面将学习的循环语句
    echo "\nAre you want to continue?(Y/N)\c"
    read reply             #读取键盘
    case $replay in
        (y|Y) break;;         #退出循环
        (n|N) echo "\n\nTerminating\n"
              exit 0;;
            *) echo "\n\nPlease answer y or n"
            continue;       #直接返回内层循环开始出继续

Example: Loop statement while, until


while/until 命令表1

The difference is that after the former executes command table 1, if the exit state is do 2 after do, and then returns to the starting point, while the latter performs command table 1 before doing something similar if the exit state is not zero. Example i.m. above.

Example: Limited loop command for


for 变量名 in 字符串表


FILE="test1.c myfile1.f pccn.h"
for i in $FILE
    cd ./tmp
    cp $i $i.old
    echo "$i copied"


Now let's take a look at the function usage at the top of the shell, first look at an example: write a function, and then call it Hello, World!

$ cat > show
# 函数定义
function show
    echo $1$2;
# 调用函数,并传给两个参数H和W
show $H $W


$ chmod 770 show

See anything wrong?

$ show $H $W

We can follow the argument directly after the function name.

The order of the ginseng corresponds to $1,$2,$3 ...

Note: What if you want to pass in a parameter, if there is a space in the middle of this parameter? Give it a try first.

to show Hello World (there is a space between two words)

function show
    echo $1
HW="Hello World"
show "$HW"

If you show $HW it $1 only Hello so the result Hello string variables must be " with .


If you are interested, continue to learn!

There are a lot of powerful things waiting, like cut expr sed awk so on.