Shell programming from understanding to open ① (Shell overview, variables, operators, conditional judgment)

Shell overview

Shell is a program written in C language, which is a bridge for users to use Linux.Shell is both a command language (which can be understood as a command line interpreter) and a programming language.

insert image description here

Shell refers to an application that provides an interface through which users access the services of the operating system kernel .

Ken Thompson's sh is the first Unix shell, and Windows Explorer is a typical GUI shell.

Shell 脚本(shell script), is a script program written for the shell.

Shell and shell script are two different concepts. The shell in the industry usually refers to shell script.

Shell environment

Shell programming is the same as JavaScript and php programming, as long as there is a text editor that can write code and a script interpreter that can interpret and execute.

There are many types of Linux shells, the common ones are:

  • Bourne Shell (/usr/bin/sh or /bin/sh)
  • Bourne Again Shell(/bin/bash)
  • C Shell(/usr/bin/csh)
  • K Shell(/usr/bin/ksh)
  • Shell for Root(/sbin/sh)
  • ...

We are using Bash here, or Bourne Again Shell, which is widely used in daily work due to its ease of use and free. At the same time, Bash is also the default shell of most Linux systems.

In general, people don't distinguish between Bourne Shelland Bourne Again Shell, so, like #!/bin/sh, it can also be changed to #!/bin/bash.

[root@hadoop101 bin]$ ll | grep bash
-rwxr-xr-x. 1 root root 941880 5 月 11 2016 bash
lrwxrwxrwx. 1 root root 4 5 月 27 2017 sh -> bash

#!Tells the system that the program specified by the following path is the shell program that interprets the script file.

Getting Started with Shell Scripting

Requirements: Create a Shell script that outputs helloworld

Open a text editor (you can use the vi/vim command to create a file), create a new file test.sh with the extension sh (sh stands for shell), the extension does not affect the execution of the script, it is good to know the name , if you Use php to write shell scripts, and use php for the extension.

Enter some code, the first line is generally like this:

#!/bin/bash
echo "Hello World !"

Common Execution Methods of Scripts:

  • The first: use the relative path or absolute path of the bash or sh+ script (without giving the script +x permission)
  • The second: execute the script with the absolute path or relative path of the input script (must have executable permission +x)

The first: use the relative path or absolute path of the bash or sh+ script (without giving the script +x permission)

relative path to sh+ script

[root@hadoop101 shells]$ sh ./helloworld.sh
Helloworld

Absolute path to sh+ script

[root@hadoop101 shells]$ sh /home/root/shells/helloworld.sh
helloworld

Relative path to bash+script

[root@hadoop101 shells]$ bash ./helloworld.sh
Helloworld

Absolute path to bash+ script

[root@hadoop101 shells]$ bash /home/root/shells/helloworld.sh
Helloworld

The second: execute the script with the absolute path or relative path of the input script (must have executable permission +x)

①First, give +x permission to the helloworld.sh script

[root@hadoop101 shells]$ chmod +x helloworld.sh

②Execute the script

relative path

[root@hadoop101 shells]$ ./helloworld.sh
Helloworld

absolute path

[root@hadoop101 shells]$ /home/root/shells/helloworld.sh
Helloworld

insert image description here

Note: The first execution method is essentially that the bash parser executes the script for you, so the script itself does not need execution permission. The second execution method, the essence is that the script needs to be executed by itself, so it needs execution permission.

Extension: The third type: add "." or source before the path of the script

①There are the following scripts

[root@hadoop101 shells]$ cat test.sh
#!/bin/bash
A=5
echo $A

②Use the methods of sh, bash, ./and respectively .to execute, and the results are as follows:

[root@hadoop101 shells]$ bash test.sh
[root@hadoop101 shells]$ echo $A

[root@hadoop101 shells]$ sh test.sh
[root@hadoop101 shells]$ echo $A

[root@hadoop101 shells]$ ./test.sh
[root@hadoop101 shells]$ echo $A

[root@hadoop101 shells]$ . test.sh
[root@hadoop101 shells]$ echo $A
5

Reason:
The first two methods open a subshell in the current shell to execute the script content. When the script content ends, the subshell is closed and returns to the parent shell.
The third method, that is, by adding "." or source before the script path, can make the script content execute in the current shell without opening a subshell! This is why we need to source it every time we modify the /etc/profile file.
The difference between opening a subshell and not opening a subshell is that the inheritance relationship of environment variables, such as the current variable set in the subshell, is invisible to the parent shell

Shell variables

Notes on using variables

To use a defined variable, just prefix the variable name with a dollar sign

We can also enclose variables in curly braces:
insert image description here

The curly braces around the variable name are optional and can be added or not. The curly braces are added to help the interpreter recognize the boundaries of the variable.Curly braces are recommended for all variables, which is good programming practice.

System Predefined Variables

Common system variables

$HOME, $PWD, $SHELL, $USERetc.

[root@hadoop101 shells]$ echo $HOME
/home/atguigu 

We can display all variables in the current shell: set
insert image description here

custom variable

basic grammar

  • Define a variable: variable name = variable value.Note that =there can be no spaces before and after the number
  • Undo variable: unset variable
  • Declare static variables: readonly variables.Note: cannot be unset

Variable Definition Rules

  • The variable name can be composed of letters, numbers and underscores, but cannot start with a number. It is recommended to capitalize the environment variable name
  • No spaces on either side of the equal sign
  • In bash, the default type of variables is string type, and numerical operations cannot be performed directly
  • If the value of the variable has spaces, it needs to be enclosed in double quotes or single quotes

Case practice

(1) Define the variable A

[root@hadoop101 shells]$ A=5
[root@hadoop101 shells]$ echo $A
5

(2) Reassign variable A

[root@hadoop101 shells]$ A=8
[root@hadoop101 shells]$ echo $A
8

(3) Cancel variable A

[root@hadoop101 shells]$ unset A
[root@hadoop101 shells]$ echo $A

(4) Declare a static variable B=2, which cannot be unset

[root@hadoop101 shells]$ readonly B=2
[root@hadoop101 shells]$ echo $B
2
[root@hadoop101 shells]$ B=9
-bash: B: readonly variable 

(5) In bash, the default type of variables is string type, and numerical operations cannot be performed directly

[root@hadoop102 ~]$ C=1+2
[root@hadoop102 ~]$ echo $C
1+2

(6) If the value of the variable has spaces, it needs to be enclosed in double quotation marks or single quotation marks

[root@hadoop102 ~]$ D=I love banzhang
-bash: world: command not found
[root@hadoop102 ~]$ D="I love banzhang"
[root@hadoop102 ~]$ echo $D
I love banzhang

(7) The variable can be promoted to a global environment variable, which can be used by other Shell programs

export 变量名
[root@hadoop101 shells]$ vim helloworld.sh

Add echo $B to the helloworld.sh file

#!/bin/bash
echo "helloworld"
echo $B
[root@hadoop101 shells]$ ./helloworld.sh
Helloworld

It is found that the value of variable B is not printed out.

[root@hadoop101 shells]$ export B
[root@hadoop101 shells]$ ./helloworld.sh
helloworld
2

special variable

$n

Basic syntax:
$n (function description: n is a number, $0 represents the script name, $1-$9 represents the first to ninth parameters, more than ten parameters, more than ten parameters need to be enclosed in curly brackets, such as ${10 })

E.g:

[root@hadoop101 shells]$ touch parameter.sh
[root@hadoop101 shells]$ vim parameter.sh
#!/bin/bash
echo '==========$n=========='
echo $0
echo $1
echo $2
[root@hadoop101 shells]$ chmod 777 parameter.sh
[root@hadoop101 shells]$ ./parameter.sh cls xz
==========$n==========
./parameter.sh
cls
xz

$#

Basic syntax :

$# (Function description: Get the number of all input parameters, often used in loops, to determine whether the number of parameters is correct and to enhance the robustness of the script).

E.g:

[root@hadoop101 shells]$ vim parameter.sh
#!/bin/bash
echo '==========$n=========='
echo $0
echo $1
echo $2
echo '==========$#=========='
echo $#
[root@hadoop101 shells]$ chmod 777 parameter.sh
[root@hadoop101 shells]$ ./parameter.sh cls xz
==========$n==========
./parameter.sh
cls
xz
==========$#==========
2

$*, $@

Basic syntax :

  • $* (function description: this variable represents all the parameters in the command line, $* treats all parameters as a whole)
  • $@ (Function description: This variable also represents all the parameters in the command line, but $@ treats each parameter differently)

Assuming that three parameters 1, 2, 3 are written when the script is running, " * " is equivalent to "1 2 3" (one parameter is passed), and "@" is equivalent to "1" "2" " 3" (three arguments are passed).

E.g:

[root@hadoop101 shells]$ vim parameter.sh
#!/bin/bash
echo '==========$n=========='
echo $0
echo $1
echo $2
echo '==========$#=========='
echo $#
echo '==========$*=========='
echo $*
echo '==========$@=========='
echo $@
[root@hadoop101 shells]$ ./parameter.sh a b c d e f g
==========$n==========
./parameter.sh
a
b
==========$#==========
7
==========$*==========
a b c d e f g
==========$@==========
a b c d e f g

$?

Basic syntax :
$? (Function description: The return status of the last executed command. If the value of this variable is 0, it proves that the previous command was executed correctly; if the value of this variable is not 0 (the specific number is determined by the command itself), then Prove that the previous command was executed incorrectly.)

For example, we judge whether the helloworld.sh script is executed correctly:

[root@hadoop101 shells]$ ./helloworld.sh
hello world
[root@hadoop101 shells]$ echo $?
0

Summarize

insert image description here

operator

Shell, like other programming languages, supports a variety of operators, including:

  • arithmetic operators
  • relational operator
  • boolean operator
  • string operator
  • file test operator

Native bash does not support simple mathematical operations, but can be achieved through other commands, such as awk and expr, expr is the most commonly used.

expr is an expression evaluation tool that can be used to evaluate expressions.

Here we only involve simple four operators, the use of other operators can be viewed:
https://www.runoob.com/linux/linux-shell-basic-operators.html

For example, we use expr to add two numbers:

insert image description here

Notice:

  • Note the use of backticks ` instead of single quotes'
  • There should be spaces between expressions and operators, for example 2+2 is wrong, it must be written as 2 + 2, which is different from most programming languages ​​we are familiar with.
  • The full expression is to be included , note that this character is not the usual single quote, below the Esc key.

The function of backticks is command substitution. The content in backticks (``) is usually the command line. The program will execute the content in the backticks first, and replace the content in the backticks with the running result.

We can also do it in another way:

"$((expression))" or "$[expression]"

insert image description here
More examples:
insert image description here

Next, we combine the previous knowledge points and run a script file to complete the addition operation:

First we create a script add.sh:
insert image description here

Then we pass in the parameters when executing the script:
insert image description here

Conditional judgment

basic grammar

  • test condition
  • [ condition ](Note that there should be spaces before and after condition)

Note: if the condition is not empty, it is true, [ root ] returns true, [ ] returns false

Common judgment conditions

  • comparison between two integers
    • -eq equals (equal)
    • -ne is not equal
    • -lt less than (less than)
    • -le less than or equal to (less equal)
    • -gt is greater than
    • -ge is greater than or equal to (greater equal)
      Note: If it is a comparison between strings, use the equal sign "=" to judge equality; use "!=" to judge inequality.
  • Judging by file permissions
    • -r has read permission (read)
    • -w has write permission (write)
    • -x has permission to execute (execute)
  • Judging by file type
    • File existence (existence)
    • The file exists and is a regular file (file)
    • The file exists and is a directory

Case practice

(1) Whether 23 is greater than or equal to 22

[root@hadoop101 shells]$ [ 23 -ge 22 ]
[root@hadoop101 shells]$ echo $?
0

(2) Does helloworld.sh have write permission?

[root@hadoop101 shells]$ [ -w helloworld.sh ]
[root@hadoop101 shells]$ echo $?
0

(3) Whether the file in the /home/atguigu/cls.txt directory exists

[root@hadoop101 shells]$ [ -e /home/atguigu/cls.txt ]
[root@hadoop101 shells]$ echo $?
1

(4) Multi-condition judgment (&& means that the next command is executed only when the previous command is executed successfully, || means that the next command is executed only after the previous command fails to be executed)

[root@hadoop101 ~]$ [ root ] && echo OK || echo notOK
OK
[root@hadoop101 shells]$ [ ] && echo OK || echo notOK
notOK

Guess you like

Origin blog.csdn.net/zyb18507175502/article/details/127490163