Bash Shell Programming Essentials Summary

Source: Internet
Author: User

I. Case ORDER

Case variable in
value1)

Command (s)
;;

value2)

Command (s)
;;

*)

Command (s)
;;

Esac

If the case variable is not matched, the program executes *) after the statement.
Shell wildcard and vertical bar (|) are allowed as the OR operator in case values

Second, if command

if command
Then

Command (s)

Fi

if test expression
Then

Command (s)

Fi

If [string/numeric expression]
Then

Command (s)

Fi

if [[String/numeric expression]
Then

Command (s)

Fi

if ((numeric expression))
Then

Command (s)

Fi

Attention:
1) If command can be nested, in case of nesting, the fi command is always used with the nearest if pairing

2. If/else command
if command
Then

Command (s)

Else

Command (s)

Fi

3. If/elif/else command
if command
Then

Command (s)

elif command

Command (s)

elif command

Command (s)

Else

Command (s)

Fi
Attention:
1) Elif=else If, but Elif does not need the fi command to correspond
2) Else block is called the default block

Third, the eval command

The eval command evaluates the command line, does a shell replacement, and executes the command line. Typically used when normal command-line parsing does not meet the requirements.

Example:

$ set a b c D
$ echo the last argument is$$#
The last argument is $4

$ eval echo the last argument is$$#
The last argument is D

[Email protected]:~$ set-x//Open bash shell debug function
[Email protected]:~$ eval echo the last argument is $$#
+ eval echo the last argument is ' $4 '
+ + echo the last argument is D
The last argument is D

Iv. Exit command

The exit command ends the script to return to the command line.
The exit command can take a return value parameter, 0 means a smooth exit, otherwise, an abnormal exit.
The return value parameter of the Exit command is saved in the $? variable.

V. IFS field separators

The shell's internal domain delimiter can be a space, tab, and line break, which can be used as a delimiter for commands in read, set, for, and so on.
Before modifying IFS, it is a good idea to save the original IFS in another variable.

Names=tom:dick:harray:john
old_ifs= $IFS
Ifs= ":"
for persons in $names
Do

Echo $persons

Done
ifs= $OLD _ifs

Six, NULL command

The null command is expressed as a built-in command that does nothing, and returns a status value of 0 (true), usually used to create an infinite loop.
Example:
If grep "Hello" hello.txt
Then

:

Else

echo "Not found!"

Fi

Seven, Shift command

The shift command is used to shift the positional parameters to a specified number of times, and the shift command without parameters shifts the parameter table to the left.
Shift [N]

while (($#>0))
Do

Echo $*
Shift

Done

Eight, circular command

Bash Shell has four loops: For loop, while loop, until loop, select Loop

1. For loop

For variable in word_list
Do

Command (s)

Done

Example:
For pal in Tom Dick Harry Joe
Do

echo "Hi $pal"

Done

For file in Memo[1-5] #world_list可以是正则表达式, but the file must exist in order to expand, otherwise do not expand
Do

......

Done

For file #word_list为空, auto-loop positional parameter, equivalent to for file in $*
Do

......

Done

2. While loop

While loop form: When command exits a status value of 0 o'clock, executes the order in the loop body (s), until the command exits the state value is not 0
While command
Do

Command (s)

Done

Example:
Num=0
while ((NUM<10))
Do

Let Num+=1
echo "Num= $num"

Done

While "$answer"! = "Bill Clinton"
Do

......

Done

While [-N ' $go '] #-n: string length not 0
Do

......

Done

While True #true命令是Linux中退出状态值永远为0的命令
Do

......

Done

3. Until cycle

1, until loop form: In contrast to the while loop, when the command exit value is non-0 o'clock, execute the order in the loop body (s), otherwise, exit the loop
Until command
Do

Command (s)

Done

Example:
Until who | grep Linda
Do

Sleep 5

Done
talk [email protected]

Num=0
Until ((NUM>10))
Do

Let Num+=1
echo "Num= $num"

Done

4. Select Cycle

The main function of the Select loop is to create the menu, and the Digitized menu appears on the standard error, PS3 (the default is #? ) Prompts the user for input.
The menu number is entered and saved to reply.
If the reply variable is empty, the menu will be re-displayed.
A variable column represents the width of the column of a menu created with the Select command displayed on the terminal, default 80.
The variable lines controls the number of lines that the menu displays vertically on the terminal, which defaults to 24, and when Lines=1, the menu is displayed on a single line.
Break command or Ctl+c exit loop,

Select Var in wordlist
Do

Command (s)

Done

Example:
Select name in Chenjy panda Xiaopang
Do

echo "Name= $name, reply= $REPLY"

Done

Output:
1) Chenjy
2) Panda
3) Xiaopang
#?

5. Break command

The built-in break command is used to exit from the loop strongly, but does not exit the program.
Break can use a number as a parameter to specify the number of loop layers that are forced to exit. If there are three layers of loops, the outermost loop is 3, the middle is 2, and the innermost layer is 1.
break [n] n default value is 1

6. Continue command

Continue [n] n default value is 1
If certain conditions are true, the continue command control jumps to the top of the loop, and all statements following the continue command are ignored.
If a number is used as an argument, control can restart execution at the top of the loop at any specified layer. If there is a three-layer loop, the outermost loop number is 3, the middle layer is 2, and the innermost is 1.

7. Io redirection in the loop

The input in the file can be redirected to a loop through the pipeline, and the output of the loop can also be redirected to a file or redirected to another program through a pipeline. The shell starts a child shell to handle IO redirects and pipelines.

Cat File | While Read line
Do

Echo $line

Done >tmp$$

For I in 7 9 2 3 4 5
Do

Echo $i

Done | Sort-n

8. Background Running cycle

Loops can run in the background, and the program can run continuously without waiting for the loop to end.

Example: & After the keyword done makes the loop run in the background. The program continues to run while the loop is running.

#!/bin/bash
For WHO in Bob Jim Joe Sam
Do

Mail $person < Memo

Done &

Nine, file check operator

Commonly used file inspection operators, can be divided into four categories:
1. File read and write execution permission check
-r filename File is readable
-W filename File writable
-X FileName File executable

2. Document Existence test
-e filename File exists
-d filename Directory exists
-F filename Non-directory normal file exists

3. File Type inspection
-B filename Block file
-C filename Character file
-L filename Symbolic link

4. File size Check
-s filename File size not 0

Ten, Trap traps command

The trap command allows you to control the behavior of your program after it receives a signal. When the specified signal number is received, execute the command quoted in quotation marks in the trap command.
Signal: A non-synchronous message that is sent by a process to another process, or that is sent to the process by the operating system after a specific health press, or by a number when an exception occurs.

Trap Command format:
Trap ' Command;command ' Signal-number
Trap ' Command;command ' signal-name

Attention:
1) The shell reads a total of two command strings, one time when the trap is set, once when the signal arrives.
2) If the command string is quoted in double quotes, the variable and command substitution are executed the first time the trap is set. If you are using single quotes, wait until the signal arrives at the trap to begin execution, only to see the execution variables and command substitution.
3) The settings for the trap are global to the script.

Example:
1) signal list
$ trap-l
1) SIGHUP 2) SIGINT 3) Sigquit 4) Sigill 5) SIGTRAP
6) SIGABRT 7) Sigbus 8) SIGFPE 9) SIGKILL) SIGUSR1
One) SIGSEGV (SIGUSR2) sigpipe) SIG ALRM) SIGTERM
(24) Sigstkflt) SIGCHLD) sigcont) SIGSTOP) SIGTSTP
) sigttin) Sigttou ) (SIGXCPU) Sigxfsz
() sigvtalrm) sigprof () sigwinch) SIGIO) SIGPWR
Sigsys) sigrtmin in+1) sigrtmin+2 (Panax Notoginseng) sigrtmin+3
, sigrtmin+4) sigrtmin+5) sigrtmin+6) sigrtmin+7
) SI grtmin+9) (sigrtmin+10) sigrtmin+11 () sigrtmin+12) sigrtmin+13
) sigrtmin+14 sigrtmin+15) SIGRTMAX-1 4) (SIGRTMAX-13) SIGRTMAX-12
() SIGRTMAX-11) SIGRTMAX-10 () SIGRTMAX-9) SIGRTMAX-8
) S IGRTMAX-6) (SIGRTMAX-5) SIGRTMAX-4 () SIGRTMAX-3) SIGRTMAX-2
() SIGRTMAX-1) Sigrtmax

2) Set Signal traps
$ Trap ' RM tmp*;exit 1 ' 0 1 2 15
Or
$ Trap ' RM tmp*;exit 1 ' exit HUP INT term

3) Ignore signal
$ trap "" 1 2

3) Signal Reset: After the trap command with a signal or a number, you can reset the signal to the default action.
$ trap 2
Or
$ trap INT

$ trap-//Recover all signals, invalid by experiment

4) Trap List
$ trap

5) Trap Nesting
$ Trap ' Trap 2 ' 2
Set the user to press two times CONTROL-C to terminate the program. First trap capture signal, second trap reset signal 2 default action-kill process

Xi. getopts Command

Positional parameters are not always valid when the script requires some command-line options, because some options require parameters, and positional parameters cannot be distinguished.
Bash inline function getopts can handle options with parameters

1. Basic usage
While Getopts:xyn:name
Do

Case name in
x) command (s);; Y) command (s);; N) echo "The argument for-n is $OPTARG"?) command (s); Esac;

Done

Description
1) x, y, and n are all options. Option x is preceded by a colon:, option n is followed by a colon:
2) Colon before option: Tell getopts silent error report
3) The colon after the option: Indicates that the option requires a parameter separated by a space and that the argument is a word that does not begin with a dash. Parameters are required for the-n option.
4) There is no dash option to tell Getopts has reached the end of the options list. When getopts has no parameters to handle, returns a non-0 exit status value, which causes the while loop to terminate.
5) Each time getopts is called, it assigns the legal option read from the positional parameter to the specified variable (name in the example) and, if it is not legal, the question mark? Assigns a value to a variable.
6) The option parameters are saved in the variable Optarg.
7) The variable optind has an initial value of 1 and increases by 1 after each command-line argument is processed getopts, so $optind=$#+1.

=-=-=-=-=
Powered by Blogilo

Bash Shell Programming Essentials Summary

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.