Chapter 6 of linuxshell programming guide ------ shell tool

Source: Internet
Author: User
Tags case statement name database
Any script should be able to create temporary files or log files. When running a script for backup, it is best to save a log file. These log files are usually retained in the file system for several weeks and will be deleted if they become obsolete. When developing scripts, you may always create some temporary files. In normal operation

Any script should be able to create temporary files or log files. When running a script for backup, it is best to save a log file. These log files are usually retained in the file system for several weeks and will be deleted if they become obsolete.

When developing scripts, you may always create some temporary files. When running the script normally, you must use a temporary file to save the information, so that it can be used as the input of another process. You can use the cat command to display or print the content of a temporary file.

When creating a log file, it is best to make it unique. you can identify these files by the date and time when the log file is created. We can use the date command to do this. In this way, the date and time can be part of the log file name.

To change the display format of the date and time, run the following command:
Date option + % format

You can use the plus sign (+) to set the display format of the current date and time. The following example shows the date in the format of day, month, and year:

Note: to include spaces in the display of dates and times, use double quotation marks.
[Root @ localhost huangcd] # date + % d % m % y
141213
[Root @ localhost huangcd] # date + % d-% m-% y
14-12-13
[Root @ localhost huangcd] # date + % A % e "" % B "" % Y
Saturday 14 August 13
[Root @ localhost huangcd] # date + % R

[Root @ localhost huangcd] # date + % T
09:30:05

An easy way to include a date in a file name is to use replacement. Add the variable containing the date format you need to the corresponding log file name.

In the following example, we create two log files, one using the date format of d, m, y, and the other using d, h, the time format of m.
[Root @ localhost huangcd] # ls-al | grep "mylog *"
-Rw-r -- 1 root 0 12-14 09:38 mylog1.141213
-Rw-r -- 1 root 0 12-14 mylog2.1409: 37
-Rw-r -- 1 root 0 12-14 mylog2.1409: 38
[Root @ localhost huangcd] # cat log
#! /Bin/bash
MYDATE = 'date + % d % m % Y'
LOGFILE =/home/huangcd/mylog1. $ MYDATE
> $ LOGFILE
MYTIME = 'date + % d % R'
LOGFILE2 =/home/huangcd/mylog2. $ MYTIME
> $ LOGFILE2

When discussing special variables earlier in this book, we introduced the variable $, which stores the process number of the current process that you are running. You can use it to create a unique temporary file in the script we run, because the process number of the script at runtime is unique. You only need to create a file and append it with $. At the end of the script, you only need to delete the temporary file with the $ extension. S h e l will resolve $ to the current process number and delete the corresponding file, without affecting the files suffixed with other process numbers.

In the following example, two temporary files are created, and operations are performed accordingly. Finally, these files are deleted at the end.
[Root @ localhost huangcd] # echo $
7771
[Root @ localhost huangcd] # ls-al | grep "hold *"
-Rw-r -- 1 root 77 12-14 09:45 hold1.12461
-Rw-r -- 1 root 77 12-14 09:45 hold2.12461
[Root @ localhost huangcd] # cat tempfiles
#! /Bin/bash
HOLD1 =/home/huangcd/hold1. $
HOLD2 =/home/huangcd/hold2. $
Df-tk> $ HOLD1
Cat $ HOLD1> $ HOLD2
# Rm/home/huangcd/*. $

Remember, this process number is only unique in the current process. For example, if I run the above script again, a new process number will be generated because I have created a new process.

If files have special purposes, you can easily find them by creating files with dates. In addition, it is easy to delete files by date, because it can be seen at a glance which file is the latest and which file is the oldest.

A signal is a message sent by the system to a script or command to notify them of an event. These events are usually memory errors, access permissions problems, or a user tries to stop your process. The signal is actually a number. The following table lists the most common signals and their meanings, as well as signal 0. we have encountered this before when creating the. logout file. This signal is the "exit shell" signal. To send a signal 0, you only need to enter exit from the command line, or use You can.

The following format can be used to send signals:
Kill [-signal no: | signal name] process ID

If the kill command is used without any signal or name, the default signal 15 is used.

You can use the following command to list all signals:
[Root @ localhost huangcd] # kill-l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN + 1 36) SIGRTMIN + 2 37) SIGRTMIN + 3 38) SIGRTMIN + 4
39) SIGRTMIN + 5 40) SIGRTMIN + 6 41) SIGRTMIN + 7 42) SIGRTMIN + 8
43) SIGRTMIN + 9 44) SIGRTMIN + 10 45) SIGRTMIN + 11 46) SIGRTMIN + 12
47) SIGRTMIN + 13 48) SIGRTMIN + 14 49) SIGRTMIN + 15 50) SIGRTMAX-14
(51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54)
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62)
63) SIGRTMAX-1 64) SIGRTMAX

Sending Signal 1 causes a process to re-read the configuration file. For example, if you are running the Domain Name Service (DNS) Daemon named and you have made some modifications to the domain name database file, you do not need to kill the daemon and restart it, you only need to use the kill-1 Command to send signal 1 to it. The Named process will re-read its configuration file.

If the system does not support the ps-ef command, you can use ps xa. To kill the process, I can use one of the following two methods:
Kill-9 157

Or
Kill-s SIGKILL 157

In some systems, you do not need to use-s, for example, kill SIGKILL 157.

Some signals can be captured by applications or scripts, and corresponding actions can be taken based on the signals. Other signals cannot be captured. For example, if a command receives signal 9, it cannot capture other signals.

When writing the s h e l script, you only need to care about the signal 1, 2, 3, and 1 5. When the script captures a signal, it may take one of the following three operations:

1) the system will not take any action.

2) capture the signal, but ignore it.

3) capture the signal and take corresponding actions.

Most scripts use the first method, which is also the method used by all the scripts in this book so far.

Trap allows you to capture signals in the script. The command is generally in the following format:
Trap name signal (s)

Among them, name is a series of operations taken after the signal is captured. In real life, name is generally a function specifically used to process captured signals. Name must be enclosed in double quotation marks. Signal is the Signal to be captured.

The script usually takes some action after capturing a signal. The most common actions include:

1) clear temporary files.

2) ignore this signal.

3) ask the user whether to terminate the script.

The following table lists some of the most common usage of trap commands:

Trap "" 23 ignores signal 2 and signal 3, and the user cannot terminate this script

Trap "commands" 2 3 if the signal 2 or 3 is captured, execute the corresponding commands command

Trap 23 reset signal 2 and 3, the user can terminate this script

You can also use single quotes ('') instead of double quotes (" "). The result is the same.

The following example starts counting once running until the user presses (Signal 2 ). In this case, the script displays the current cyclic number and then exits.

In this example, the format of the t r a p command is:
Trap "do_something" signal no :( s)

The script is as follows:
[Root @ localhost huangcd] # sh trap1
1
2
3
4
You just hit ctrl + d, at number 4
I will now exit
[Root @ localhost huangcd] # cat trap1
#! /Bin/bash
Trap "my_exit" 2
LOOP = 0
My_exit ()
{
Echo "you just hit ctrl + d, at number $ LOOP"
Echo "I will now exit"
Exit 1
}
While:
Do
LOOP = 'expr $ LOOP + 1'
Echo $ LOOP
Sleep 3
Done

In the following example, after the script captures signal 2, it will provide you with a choice to ask whether the user really wants to exit. The case statement is used to determine the operation.

If the user wants to exit, he or she can select 1. at this time, the current function will exit with status 1, and the other clearing process will start accordingly. If you do not want to exit, you can select 2 or do not make any choice. in this case, the case statement will return the user to the original place in the script. The case statement must contain null strings entered by the user.
After receiving the signal, the following function will provide you with a selection:

When the above script is run, you only need to press You will get a choice: continue running or exit.
[Root @ localhost huangcd] # cat trap4
#! /Bin/bash
Trap "my_exit" 1 2 3 15
LOOP = 0
HOLD1 =/home/huangcd/HOLD1. $
HOLD2 =/home/huangcd/HOLD2. $
My_exit ()
{
Echo-e "\ nRecieved interrupt ....."
Echo "Do you wish to really exit ??? "
Echo "Y: yes"
Echo "N: no"
Echo-n "Your choice [Y .. N]>"
Read ANS
Case $ ANS in
Y | y) exit 1 ;;
N | N );;
Esac
}
Echo-n "Enter your name :"
Read NAME
Echo-n "Enter your age :"
Read AGE
[Root @ localhost huangcd] # sh trap4
Enter your name: huang chengdu
Enter your age: 24
[Root @ localhost huangcd] # sh trap4
Enter your name: huang
Enter your age:
Recieved interrupt .....
Do you wish to really exit ???
Y: yes
N: no
Your choice [Y .. N]> y
[Root @ localhost huangcd] # sh trap4
Enter your name:
Recieved interrupt .....
Do you wish to really exit ???
Y: yes
N: no
Your choice [Y .. N]> n
Huang
Enter your age: 12

The following script is another example of capturing signals. The script is named lockit, which uses a continuous while loop to lock the terminal. In this script, the trap command captures signals 2, 3, and 1 5. If a user attempts to interrupt the running of the script, an error is returned.

When the script is executed for the first time, a password is prompted. No prompt is prompted when unlocking the terminal. you can directly enter the password and press the Enter key. The script reads the entered password from the terminal and compares it with the preset password. if the password is consistent, the terminal is unlocked.

If you forget your password, you have to log on to another terminal and kill the process. In this example, the length of the password is not limited-it depends entirely on you.

If you have killed this process from another terminal, when you return to this terminal again, you may encounter terminal setup problems, such as the enter key does not work. In this case, you can try to use the following command to solve most of the problems.
$ Stty sane

The following is the script.
[Root @ localhost huangcd] # cat lockit
#! /Bin/bash
Trap "nice_try" 2 3 15
TTY = 'tty'
Nice_try ()
{
Echo "Nice try, the terminal stays locked"
}
SAVEDSTTY = 'stty-G'
Stty-echo
Echo-n "Enter your password to lock $ TTY :"
Read PASSWORD
Echo-n "starting \ n"
While:
Do
Read RESPONSE
If ["$ RESPONSE" = "$ PASSWORD"]
Then
Echo "unlocking"
Break
Fi
Echo "wrong password and terminal is locked"
Done
Stty $ SAVEDSTTY
[Root @ localhost huangcd] # sh lockit
Enter your password to lock/dev/pts/1: starting \ nwrong password and terminal is locked
Unlocking

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.