Linux Notes-Chapter 12th Shell Scripts

Source: Internet
Author: User
Tags arithmetic operators time and seconds

Blog Address: http://www.moonxy.com

First, preface

Common programming languages are divided into two categories: one is compiled languages, such as C, C + +, and Java, which are compiled by compilers before they travel. The other is an interpreted language, which does not need to be compiled, and when executed, it needs to be interpreted on a line by the interpreter, such as awk, Perl, Python, and Shell.

The Shell is a scripting language, which belongs to the second language mentioned above, it must have a corresponding interpreter to execute these scripts, the most common script interpreter is: Bash.

When we write shell scripts, we not only use a lot of syntax rules such as Linux commands, regular expressions, pipe characters, data flow redirection, but also we need to have the internal functions modularized and processed through logical statements, and eventually form common shell scripts.

1.1 Viewing the Shell types supported by the system

There are many types of Shell in Linux, common:
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)

You can see all the shell types and paths supported by the current system by looking at/etc/shells, as follows:

[Email protected] ~]# cat/etc/shells
/bin/sh
/bin/bash
/sbin/nologin
/bin/dash
......

The Bourn shell was one of the first shell versions to be popular, and its founder was Steven Bourn, who was named the Bourn Shell to commemorate him, referred to as SH. The Linux distributions of the RedHat series also have bash installed by default, the Bourne Again Shell, which is widely used in daily work due to its ease of use and free. At the same time, Bash is the default Shell for most Linux systems.

1.2 Viewing the Shell types used by the current user

You can view it by performing the Echo $SHELL as follows:

[Email protected] ~]# echo $SHELL
/bin/bash

Or view the/etc/passwd to see the root user's Shell type as an example, as follows:

[Email protected] ~]# CAT/ETC/PASSWD | grep ^root
Root:x:0:0:root:/root:/bin/bash

Last: The field displayed after the number is the login shell type of the root user, which is bash.

You can also directly enter the command echo $ to view, but note that not all shells are supported, as follows:

[Email protected] ~]# Echo
-bash

Of course, it can also be viewed in the current environment variable, as follows:

[Email protected] ~]# env | grep SHELL
Shell=/bin/bash

In fact, there are many ways to view the current user Shell types.

1.3 Viewing the Shell version

After obtaining the type of shell that is currently in use, the user can get its version number directly using the shell-related command parameters, and you can generally use the--version parameter to get the shell version number, as follows:

[Email protected] ~]# bash--version
GNU Bash, version 4.1.2 (1)-release (X86_64-REDHAT-LINUX-GNU)
Copyright (C) Software Foundation, Inc.
License gplv3+: GNU GPL version 3 or later

This was free software; Redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Second, the common Shell operation

2.1 Command Date

Common formatting options for the date command:

Date +%y: Indicates the year is printed in a four-digit number format;

[Email protected] ~]# date +%y
2018

Date +%y: Indicates the year is printed in a two-digit number format;

[Email protected] ~]# date +%y
18

Date +%m: Indicates the month;

[Email protected] ~]# date +%m
04

Date +%d: Represents the day;

[Email protected] ~]# date +%d
14

Date +%h: Indicates the hour;

[Email protected] ~]# date +%m
13

Date +%m: Indicates minutes;

[Email protected] ~]# date +%m
04

Date +%s: Indicates seconds;

[Email protected] ~]# date +%s
46

Date +%w: Represents the week, if the result shows that 0 indicates Sunday;

[Email protected] ~]# date +%w
6

Date +%f: Indicates the date of the month;

[Email protected] ~]# date +%f
2018-04-14

Date +%t: Indicates the time and seconds;

[Email protected] ~]# date +%t
14:08:57

Date + "%y-%m-%d%h:%m:%s", shown below:

[[Email protected] ~]# date + "%y-%m-%d%h:%m:%s"
2018-04-14 14:10:43

Date + "%F%T", shown with the same as above.

Sometimes the day before is used, as follows:

[[email protected] ~]# date-d "-1 Day" + "%d"
13

Or the date after the day, as follows:

[[email protected] ~]# date-d "+1 Day" + "%d"
15

Similarly, you can set hours, minutes, and so on.

2.2 Mathematical operations

Use [] to enclose the mathematical operation, and precede the symbol $

[Email protected] ~]# a=2;b=3
[Email protected] ~]# ab=$[$a + $b]
[Email protected] ~]# echo $ab
5

The format for defining variables is:

Variable name = variable Value

After defining a reference to the variable, add the symbol $, as follows:

$ab

If the value of a variable is a shell command, you need to add an anti-quote, which acts as a shell command to execute the string in quotation marks.

2.3 and user interaction

The read command is used to interact with the user, which takes a user-entered string as a variable value. As follows:

[email protected] shelltest]# cat readtest.sh
#!/bin/bash
# # This Shell script was used for testing read
Read- P "Please input a number:" N
Echo $n

[Email protected] shelltest]#./readtest.sh
Please input a number:5
5

You can also add the-t option, set to exit after 3 seconds, as follows:

Read- T 3 -P "Please input a number:" N

2.4 Special variables for Shell script presets

The difference between $* and [email protected] is that $* and [email protected] All represent all parameters passed to a function or script, and are not enclosed by double quotation marks (""), with "$" "$" ... All parameters are output in the form "$n". But when they are enclosed in double quotation marks (""), "$*" takes all the parameters as a whole and outputs all parameters in the form of "$ $ ... $n"; "[email protected]" separates the various parameters to "$" "$" ... All parameters are output in the form "$n".

$? You can get the exit status of the previous command. The so-called exit status is the return result after the last command was executed. Exit status is a number, in general, most of the command execution succeeds returns 0, and the failure returns 1.

2.5 Escape characters

The escape characters that can be used in echo are:

2.6 The quotes in the Shell

The quotes in the Shell are mostly single quotes , double quotes , and anti-quotes .

Single quotation marks

Any character in a single quotation mark is output as is, and the variable in the single-quote string is not valid;

Single quotation marks cannot appear in single quote strings (not after using escape characters for single quotes).

Double quotes

You can have variables in double quotes;

Escape characters can appear in double quotes.

Anti-Quote

Strings in anti-quotes are executed as shell commands.

Get the file name, using basename, as follows:

[Email protected] shelltest]# basename /root/linux/shelltest/fortest.sh
fortest.sh

Get the directory name, using dirname, as follows:

[Email protected] shelltest]# dirname /root/linux/shelltest/fortest.sh
/root/linux/shelltest

2.7 Executing the Shell

There are two ways to execute the Shell, as follows:

The first type:

SH filename.sh

The second type:

./filename.sh(requires execute permission, so it is generally necessary to grant X permissions first)

Third, Shell operators

3.1 Arithmetic operators

Native bash does not support simple math operations, but can be implemented with other commands, such as awk and expr. The following is done with expr; expr is an expression calculation tool that can be used to perform evaluation of an expression;

3.2 Relational operators

Only numbers are supported and strings are not supported, unless the value of the string is a number. Common ones are:

3.3 Boolean operators

- o(--or, can also be used [$a-lt] | | [$b-GT]),-A (--and, can also be used [$a-lt] && [$b-gt 100])

3.4 String Operators

It is commonly used to have- Z, to determine whether the value of a variable exists, does not exist to return true, and the presence returns false.

3.5 File Test Operators

Commonly used is- e(--exist, determine whether a file or directory exists),-D(--directory, determine whether the directory already exists),-F(--file, Determine if the normal file already exists)

Iv. Process Control in the Shell

4.1 If condition selection

[email protected] shelltest]# cat iftest.sh
#! /bin/bash
# # This shell script was used for testing if
echo "File name $ (basename $)"
echo "Hello $"
echo "Hello $*"
echo "Args count: $#"
argscount=$#
If [$argscount-eq 3];
Then
Echo ' args count is correct '
elif [$argscount-gt 3];
Then
Echo ' args count is more than 3 '
Else
Echo ' args count is less than 3 '
Fi

Run as follows:

[[Email protected] shelltest]# SH iftest.sh 3 5 A
File name iftest.sh
Hello 3
Hello 3 5 A
Args Count:3
Args count is correct
[[Email protected] shelltest]# SH iftest.sh 3 5
File name iftest.sh
Hello 3
Hello 3 5
Args Count:2
Args count is less than 3
[[Email protected] shelltest]# SH iftest.sh 3 5 a B
File name iftest.sh
Hello 3
Hello 3 5 A B
Args Count:4
Args count is more than 3

4.2 Case Condition Selection

[email protected] shelltest]# cat casetest.sh
#!/bin/bash
# # This shell script was used for testing case
Read-p "Input a number:" N
a=$[$n%2]
Case $a in
1)
echo "The number is odd."
;;
0)
echo "The number is even."
;;
*)
echo "It ' s not a number!"
;;
Esac

Run as follows:

[Email protected] shelltest]# sh casetest.sh
Input a Number:4
The number is even.
[Email protected] shelltest]# sh casetest.sh
Input a Number:5
The number is odd.

4.3 While loop

[email protected] shelltest]# cat whiletest.sh
#!/bin/bash
# # This shell script was used for testing while
A=5
While ["$a"-ge "1"]; Do
Echo $a
a=$[$a-1]
Done

Run as follows:

[Email protected] shelltest]# sh whiletest.sh
5
4
3
2
1

4.4 For Loop

[email protected] shelltest]# cat fortest.sh
#!/bin/bash
# # This shell script was used for testing for

For file in ' Ls/root/linux/shelltest ';
Do
ls-ld/root/linux/shelltest/$file
Done

Run as follows:

[Email protected] shelltest]# sh fortest.sh
-rwxr-xr-x 1 root root 233 Apr 17:33/root/linux/shelltest/casetest.sh
-rw-r--r--1 root root (APR) 20:49/root/linux/shelltest/field.properties
-rwxr-xr-x 1 root root 141 Apr 17:40/root/linux/shelltest/fortest.sh
-rwxr-xr-x 1 root root 211 Apr 20:48/root/linux/shelltest/funcomp.sh
-rwxr-xr-x 1 root root 235 Apr 20:47/root/linux/shelltest/funtest.sh
-rwxr-xr-x 1 root root 321 Apr 20:46/root/linux/shelltest/iftest.sh
-rwxr-xr-x 1 root root 101 Apr 14:37/root/linux/shelltest/readtest.sh
-rwxr-xr-x 1 root root 113 Apr 20:46/root/linux/shelltest/whiletest.sh

4.5 Introducing other shells

Method One: Use .

#!/bin/bash
. firstshell.sh
Echo ' Your is in second file '

Method Two: Use source

#!/bin/bash
SOURCE firstshell.sh
Echo ' Your is in second file '

4.6 Interrupts and continuation in the Shell

Break, used in a loop, to exit the layer loop to the previous layer;

Continue, used in the loop, means the end of the cycle, the start of the next cycle;

Exit, used anywhere, to exit the shell script;

Return, used in the function, means return, Exit function;

These commands have the same effect as the corresponding keywords in C, Java, and other languages.

Linux Notes-Chapter 12th Shell Scripts

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.