Shell Script - Bash

xiaoxiao2021-03-06  39

Bash (bourne again shell) is a shell developed by GNU, is named by the shell developed by Steve Bourne, is to replace the general commercial shell by bash. The idea of ​​Shell has appeared at UNIX Version 7, and its version is a Bourne Shell, which is SH.

Later, Bill Joy (very familiar? He is the author of VI, is also one of the important people developed by BSD) C shell is more widely used, because c shell's grammar is like C, administrators only need Know the C program simply use C shell. For establishing a GNU system, it is necessary to write a shell housing, and Bash is written by Brian Fox (the people named GNU) and maintained by Chet Ramey. At present, the latest version is 2.04.

Now, most of the Linux Distribution presets use BASH, while other systems use traditional CSH (c shell) or KSH (Korn shell) like OpenBSD and FreeBSD. And the author introduces Bash, focusing on the program on BASH (ie shell script), and the application of the Bash environment will only mention instead of explaining, because writing shell script has a great help.

The first shell script

In many cases, the system uses shell script, such as /etc/rc.d/rc.local ,.bash_login, etc., and even the time check with ISP can use the help of Shell Script. Please see the example 1. 'Echo' is printing the words or variables. In the programming of Bash, it is variable with $ start, I believe that friends who use Perl can understand it! The example is to print this sentence:

Example No. 1 (TEST-1.SH):

#! / bin / bash

Var1 = "how are you today?"

Echo $ VAR1

First of all, please pay attention, in the first line of Test-1.sh, the author set it to / bin / bash execution, not / bin / sh, the cause may be part of the UNIX system / bin / sh is not Bash, this execution may have problems, so you still check it, if / bin / sh is the Symbolic Link to / bin / Bash, can be used.

The variables in Bash are much smoldering sensitive, ie, $ VAR inequality to $ VAR, this is the same language. After storeing Test 1.sh, there are two ways, you can use Bash to execute this file, or set the file to executable:

Example An execution method one:

Shell @ www: ~ # Sh Test 1.sh how are you today?

Example 1 Method 2:

Shell @ www: ~ # chmod 0700 test-1.sh

Shell @ www: ~ # ./test-1.sh

How are you today?

Both methods are feasible, in different cases, you can choose which method is better.

BASH programming support parameters (Parameters). On C, you can use Argc and Argv to find the parameters of the program; on Bash, $ # is argc, which is the number of display parameters; and $ 1, $ 2, $ 3, etc. is the parameter value, $ @ It is an array of all parameters (array). Please refer to the example.

#! / bin / bash

Echo "Total Parameters of $ 0: $ #"

Echo "They Are: $ @";

Echo "First Parameter IS: $ 1"

Example two execution method:

Shell @ www: ~ # chmod 700 Test-2.sh

Shell @ www: ~ # ./test-2.sh 1st 2nd 3rd

Total parameters of ./test.sh: 3

THEY Are: 1st 2nd 3rd

First Parameter IS: 1ST

In Example III, we tried to use the shell script to perform external programs. It is a shell script that looks a string in a file:

Example 3 (Test-3.sh):

#! / bin / bash

Echo "Now Searching File: $ {1 ## / * /}"

GREP $ 2 $ 1

Example three execution method:

Shell @ www: ~ # ./test-3.sh / etc / service ftp

Now Searching File: Services

FTP-DATA 20 / TCP

FTP 21 / TCP

TFTP 69 / UDP

SFTP 115 / TCP

BFTP 152 / TCP

The parameter first is the file location, and the parameter 2 is a string. In this shell script with two lines, there is no special feature, the purpose is just how to perform external instructions in the shell script. Or we can make the examples complicated, of course, please continue to look. The $ {1 ## / * /} in the example is to delete / etc / etc., Please refer to Table 1.

Table I:

Variable result $ {path} / usr / local / bin / emacs $ {path # / * /} local / bin / emacs $ {pat ## / * /} Emacs $ {Path% / *} / usr / local / bin $ {pat: 15} Emacs $ {Path: 10: 4} / bin

In addition, in Bash's variables, there are some instant return tests, such as whether the test variable exists, if not, it will do something else, these shell script written in writing, please refer to Table 2 (here first Suppose the value of $ VAR1 is "YES", and $ VAR2 is not defined):

Table II:

Usage results $ {var1: -no} Print "no" $ {var2: -yes} var 2 has no variable value, print "YES" string $ {var 1: = no} Print "YES" string $ {var2 : = Yes} VAR2 The variable value is "YES" $ {var1:? No} Prints "YES" string $ {var2:? Yes} Print "VAR2: YES" word

By the way, if you enter the echo -e $ {patH //: / '} in the shell environment, the printed is the value in the $ PATH variable, and /: /' 'will separate $ PATH ': The' string changed to newline printing. Editor Note: To be aware of the replacement of all the above variables, see a section of "Parameter Expansion" in the BASH MANPAGE.

IF ... then ... else ... Fi

grammar:

IF ; THEN

Execute instructions

Elif ; THEN

Execute instructions

Else

Execute instructions

IF

In Example 4, we joined the conditional control of IF, making the shell script function becomes better; maybe in front of the example, the table three is the comparison character and test word in Bash:

Table 3:

Usage Interpretation Str1 = STR2 Comparison String Variable Whether the STR1! = STR2 Compare String Variables Different Str1 STR2 Comparison STR1 is less than STR2-N STR1 Check whether STR1 is defined - z str1 Check STR1 Not defined

Example 4 (TEST-4.SH):

#! / bin / bash

IF [-z "$ 1"]; then

echo "Usage: Test-4.sh [file] [keyword]"

EXIT 1;

Fi

Echo "Now Searching File: $ {1 ## / * /}"

GREP $ 2 $ 1

We use -z to check $ 1, that is, the first parameter, if there is no input parameters, the program will return to the method used, then end the program execution; of course, we can also add more more checks, making this program more Strong. In Example 5, we joined the inspection of the file status.

Example 5 (TEST-5.SH):

#! / bin / bash

IF [$ #! = "2"]; then

Echo "Usage: Test-5.sh [file] [keyword]"

EXIT 1;

Fi

IF [! -r "$ 1"];.

Echo "No Such Files or Permission Denied!"

Fi

Echo "Now Searching File: $ {1 ## / * /}"

GREP $ 2 $ 1

In Example 5, a piece of IF is added, "!" Means not, that is, check if $ 1 cannot be read (! -R), just like Slackware's RC file will be tested in /etc/rc.d/ There is no RC. * File, and check if it can be executed, the operator of these checks, you can refer to Table 4:

Table 4:

Option Interpretation -D Check that Directory -E Checks File -f Check if files (non-special files such as / dev / *) - r Check if you read -s -s checking files or whether the content is not empty -w check -X Check if -O check Owner is the executor -g check group is the executive group

Editor's Note: If you want to know more, please refer to the MANPAGE of Test.

Example 6 (TEST-6.SH):

#! / bin / bash

FILENAME = "Test-6.sh"

Echo -n "File Owner of $ FileName IS" IF [-o $ filename]; then

echo "you!"

Else

echo "not you!"

Fi

Example Six is ​​another example of checking files. It is similar to the previous example. Only, it is necessary to pay attention to the -n parameter in echo. It will not open a new line.

For ... in ...; do ...; done

grammar:

For x in list

DO

Execute instructions

DONE

For loop is very common in some cases, for example, when working in a lot of directory. Please refer to the example seven; it is a very simple shell script, the role is just to find the file name of the string in several directories:

Example 7 (TEST-7.SH):

#! / bin / bash

IFS =:

PATH = / usr / bin: / usr / sbin: / sbin: / bin: / usr / local / sbin: / usr / local / bin

IF [-z "$ 1"]; then

echo "Usage: Test-7.sh [keyword]"

EXIT 1

Fi

For Dir in $ PATH

DO

echo "Working in $ DIR ..."

LS -AL $ DIR | GREP $ 1

DONE

EXIT 0

Example seven execution method:

Shell @ www: ~ # ./test-7.sh login

Working in / usr / bin ...

-R-SR-XR-X 1 root bin 20480 DEC 24 13:29 login

-R-SR-XR-x 1 root bin 20480 dec 24 13:18 rlogin

-R-SR-XR-x 2 root bin 184320 Feb 1 10:13 Slogin

Working in / usr / sbin ...

-R-SR-XR-X 1 root bin 12288 DEC 24 13:19 Sliplogin

Working in / sbin ...

-R-XR-XR-X 1 root bin 20480 DEC 24 13:18 NOLOGIN

Working in / bin ...

Working in / usr / local / sbin ...

Working in / usr / local / bin ...

Case ... in ... ESAC

grammar:

Case in

Pattern 1)

Executive instruction;

Pattern 2)

Executive instruction;

ESAC

Case is like Select in the C language, its process is pairing in [Expression] and [Pattern], if you find a statement within [Pattern]; the most common example of using Case is Redhat, etc. INIT Script, when entering '/etc/rc.d/init.d/network restart', the program performs different statements in response to 'start', 'stop', 'restart'.

In Example Eight is a shell script that uses CASE to control the network interface card.

Example 8 (TEST-8.SH):

#! / bin / bash

IP = 202.181.234.40

Eth = eth0

Case "$ 1" in

UP)

IFCONFIG $ Eth Up ;;

Down

IFCONFIG $ Eth Down ;;

Test)

PING $ IP ;;

*)

Echo "Usage {UP | DOWN | TEST}"

echo

ESAC

EXIT 0

While and unsil

While syntax:

While

DO

DONE

In some work, you will need to use a constant loop to check the variable changes. If you have experience in using other programming languages, I believe that whilele is not stranger; please refer to the example nine, it uses new features, it is getopts, getopts in the C program has the same function as the same function, used to get The parameter of the program.

Example Nine (TEST-9.SH):

#! / bin / bash

While getopts "a: b: c" opt; do

Case $ OPT IN

a) echo -n "argv is -a!" ;;

b) echo -n "argv is -b!" ;;

c) echo -n "argv is -c!" ;;

*) Echo "Usage: $ 0 - [abc] text"

EXIT 1 ;;

ESAC

DONE

ECHO $ ​​2

Example Nine Execution Method:

Shell @ www: ~ # ./test-9.sh -a "the sting here"

Rgv is -a! The string here

Of course, the example nine is not a good program, just want to introduce how WETOPTS is used and used. The situation that WHILE and GETOPTS are used and is not rare.

Until syntax:

Until ; DO

DONE

The usage of UnTIL and WHILE is very similar, so the author does not introduce, but generally Until will be used in a state in which the inspection instruction is executed.

FUNCTION

When the article starts, the author mentioned that there is a function function in Bash, which is a subroutine, which is often used in general writing, but there will be fewer writing when writing shell script; there are many benefits that use subroutines, such as When the program is more complicated, or some statements need to be repeated, and the subscriber is necessary.

grammar:

Function name

{

}

Or

Name () {

}

'name' is the name of the subroutine, and the method of executing is direct call 'name', any parameter input to the subroutine can be added behind the 'Name', such as:

#! / bin / bash

Function Test

{

Echo "Test ..."

}

Test

or

#! / bin / bash

Function Test

{

Echo "Argument IS $ 1"

}

Test ABC

Conclusion

In fact, in Bash's program design, there are still many functional author not introduced. I hope to introduce it for you next time; if you want to learn more about Shell Script, you can refer to O'Reilly Published Learning The Bash Shell or the original Shell script and manpage on the system, you will learn the use of other functions. Wen: shell hung shellhung@linux.org.hk

转载请注明原文地址:https://www.9cbs.com/read-71753.html

New Post(0)