Linux Shell advanced skills (1)

Source: Internet
Author: User

This series will focus on the advanced usage skills in Linux Shell. It is mainly intended for experienced Shell developers, Linux system administrators, and Linux enthusiasts. The examples in the blog mainly come from the Internet and some classic books. After my collection and sorting, they are presented to you in the form of series blogs. If you have more and better typical Shell script examples and want to share them with us, you can contact me by email or blog reply, I will try my best to ensure that the series is continuously updated.

1. Convert the input information into uppercase characters before performing conditional judgment:

After reading the user's normal input, it is very likely that the input information will be used for condition judgment. Therefore, we will have to consider the case matching problem of the information during the comparison.

/> Cat> test1.sh

#! /Bin/sh
Echo-n "Please let me know your name ."
Read name
# Output the value of the variable name to the tr command through the MPs queue. Then, the tr Command performs case-sensitivity conversion and then assigns a new value to the name variable.
Name = 'echo $ name | tr [a-z] [A-Z]'
If [[$ name = "STEPHEN"]; then
Echo "Hello, Stephen ."
Else
Echo "You are not Stephen ."
Fi
CTRL + D
/>./Test1.sh
Please let me know your name.Stephen
Hello, Stephen.

2. Set the output level for debugging information:

We often add necessary debugging information when debugging scripts to track errors in the program. After debugging is completed, the additional debugging information is usually deleted. After a while, if the script needs to add new functions, we will have to re-debug the script, in this way, you may need to add the debugging information. After successful debugging, the information may be deleted again. If we can add a debugging level for our debugging information so that it can be output only when necessary, I think this will be a very pleasant thing.
/> Cat> test2.sh
#! /Bin/sh
If [[$ # = 0]; then
Echo "Usage:./test2.sh-d debug_level"
Exit 1
Fi
#1. Read the command line option parameter of the script and assign the option value to the variable argument.
While getopts d: argument
Do
#2. It is valid only when the option is d (-d). At the same time, assign the parameter ($ OPTARG) after-d to the variable debug, indicating the debugging level of the current script.
Case $ argument in
D) debug_level = $ OPTARG ;;
\?) Echo "Usage:./test2.sh-d debug_level"
Exit 1
;;
Esac
Done
#3. If the debug value is null or is not a number between 0 and 9, assign the default value 0 to the debug variable.
If [[-z $ debug_level | $ debug_level! = [0-9]; then
Debug_level = 0
Fi
Echo "The current debug_level level is $ debug_level ."
Echo-n "Tell me your name ."
Read name
Name = 'echo $ name | tr [a-z] [A-Z]'
If [$ name = "STEPHEN"]; then
#4. Determine whether to output the debugging information based on the debugging level of the current script. At this time, when debug_level> 0, the debugging information is output.
Test $ debug_level-gt 0 & echo "This is stephen ."
# Do something you want here.
Elif [$ name = "ANN"]; then
#5. output the debugging information when debug_level> 1.
Test $ debug_level-gt 1 & echo "This is ann ."
# Do something you want here.
Else
#6. output the debugging information when debug_level> 2.
Test $ debug_level-gt 2 & echo "This is others ."
# Do any other else.
Fi
CTRL + D
/>./Test2.sh
Usage:./test2.sh-d debug_level
/>./Test2.sh-d 1
The current debug level is 1.
Tell me your name.Ann
/>./Test2.sh-d 2
The current debug level is 2.
Tell me your name.Ann
This is ann.

3. Determine whether the parameter is a number:

Sometimes we need to verify whether the parameters of the script or the values of some variables are numbers. If not, we need to give a prompt and exit the script.
/> Cat> test3.sh
#! /Bin/sh
#1. $1 is the first parameter of the script. It is passed to the awk command as the first parameter of the awk command.
#2. Because no input file is used as the input stream, it is only completed in the BEGIN block.
#3. In awk, The ARGV array indicates the parameter array of the awk command, ARGV [0] indicates the command itself, and ARGV [1] indicates the first parameter.
#4. match is a built-in function of awk. The returned value is the starting position of the matched Regular Expression in the string (ARGV [1]). If no value is found, 0 is returned.
#5. The regular expression has ensured that the matched string must be a positive integer in decimal format. If you need a floating point or a negative number, you only need to modify the regular expression.
#6. After awk is executed, return the result to the isdigit variable and use it as its initialization value.
#7. isdigit = 'echo $1 | awk' {if (match ($1, "^ [0-9] + $ ")! = 0) print "true"; else print "false "}''
#8. The above method can also implement this function, but because there are multiple processes involved, the efficiency is lower than the following method.
Isdigit = 'awk' BEGIN {if (match (ARGV [1], "^ [0-9] + $ ")! = 0) print "true"; else print "false"} '$1'
If [[$ isdigit = "true"]; then
Echo "This is numeric variable ."
Number = $1
Else
Echo "This is not numeric variable ."
Number = 0
Fi
CTRL + D
/>./Test3.sh 12

This is numeric variable.
/>./Test3.sh 12r
This is not numeric variable.

4. Judge the parity of integer variables:

In order to simplify the problem and highlight the key points, we assume that the input parameters of the script must be of valid integer type, so the parameter legality is not determined within the script.
/> Cat> test4.sh
#! /Bin/sh
#1. the focus here is mainly on writing regular expressions in the sed command. It splits the original number into two modes (split with parentheses), one for all the preceding high numbers, the other is the last low digit. Then, use the replacement character (\ 2) to replace the original digit with the last digit. Finally, return the result as the last_digit variable.
Last_digit = 'echo $1 | sed's/\ (. * \) \ (. \) $/\ 2 /''
#2. If the last_digit value is 0, 2, 4, 6, 8, it indicates an even number; otherwise, it indicates an odd number.
Case $ last_digit in
0 | 2 | 4 | 6 | 8)
Echo "This is an even number .";;
*)
Echo "This is not an even number .";;
Esac
CTRL + D
/>./Test4.sh 34
This is an even number.
/>./Test4.sh 345
This is not an even number.

5. Assign Shell commands to specified variables to ensure script Portability:

Sometimes, when we execute a command in a script, different operating systems may lead to different command paths, or even different command names or options, to ensure better platform portability of scripts, we can assign the command of this function to the specified variable, and then directly use this variable when using this command. In this way, when more operating systems are added in the future, we only need to assign different values to the variable based on the new system. Otherwise, we will have to modify more places, this can easily lead to bugs caused by incorrect modification.
/> Cat> test5.sh
#! /Bin/sh
#1. Use the uname command to obtain the current system name. Then, assign the full name of the PING command to the ping Variable Based on the OS name.
Osname = 'uname-S'
#2. You can add more operating system names in the case condition.
Case $ osname in
"Linux ")
PING =/usr/sbin/ping ;;
"FreeBSD ")
PING =/sbin/ping ;;
"SunOS ")
PING =/usr/sbin/ping ;;
*)
;;
Esac
CTRL + D
/> ../Test5.sh
/> Echo $ PING
/Usr/sbin/ping

6. Obtain the number of days that the current time has elapsed since the epoch time (January 1, January 1, 1970:

When obtaining the difference between two time points, you need to consider many issues, such as the number of days in a leap year or month. However, if we can determine the difference in the number of days between two time points, it is very easy to calculate the difference between time and minute and second. In the C language function provided by the system, the obtained time value is the number of seconds that flows from 0 to the current time on January 1, January 1, 1970. If we calculate the difference of the number of days between the two time periods based on this, this will greatly simplify our calculation formula.
/> Cat> test6.sh
#! /Bin/sh
#1. Assign the execution result of the date command (second minute hour day month year) to the array variable DATE.
Declare-a DATE = ('date + "% S % M % k % d % m % Y "')
#2. To improve efficiency, this directly shows the number of days constant that flows through the January 1, 1970 s to the new era.
Epoch_days = 719591
#3. Extract the time score from the array.
Year =$ {DATE [5]}
Month =$ {DATE [4]}
Day =$ {DATE [3]}
Hour =$ {DATE [2]}
Minute =$ {DATE [1]}
Second =$ {DATE [0]}
#4. when the month value is 1 or 2, add the value of the month variable plus one. Otherwise, add the month value to 13 and the value of the year variable to one, this is mainly because of the need to take the average number of days of a month in the following formula.
If [$ month-gt 2]; then
Month = $ (month + 1 ))
Else
Month = $ (month + 13 ))
Year = $(year-1 ))
Fi
#5. The year variable is involved in the calculation of the leap year problem. You can google this problem on your own.
#6. The month variable is mainly used to calculate the average number of days in a month.
#7. The calculation result is the number of days that the current date flows through the new century.
Today_days = $ (year * 365) + (year/4)-(year/100) + (year/400) + (month * 306001/10000) + day ))
#8. The total number of days minus the number of days from the epoch in the new century can be the number of days we need.
Days_since_epoch = $ (today_days-epoch_days ))
Echo $ days_since_epoch
Seconds_since_epoch = $ (days_since_epoch * 86400) + (hour * 3600) + (minute * 60) + second ))
Echo $ seconds_since_epoch
CTRL + D
/> ../Test6.sh
15310
1322829080
It should be noted that it is recommended to put the content of this script into a function, so that we can use it for computing similar time data in the future.

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.