Linux Shell Usage Notes

Source: Internet
Author: User
Tags error handling exit in what integer

1. Background

The Linux shell is a basic skill, because the weird syntax, combined with poor readability, is often replaced by scripts such as Python.

Since it is the basic skills, it needs to be mastered. After all, the process of learning shell scripts, you can still learn a lot of Linux system content. Linux scripting Masters are not accessible to everyone. However, it is necessary to implement some common basic functions with some simple shells.

2. The subject

1) Warm Up

The following example shows how to pass the arguments to the script, how the script gets the arguments, the if-else inference, the use of variables, and the like.

#!/bin/bashif [[$#-lt 1]]; Then        echo "args count must > 1"        echo "Uage:bash +x example01.sh [args ...]"        exitfiarg=$1if [[$arg-GT 10]]; Then        echo "$arg >" Else        echo "$arg <" fi
The way this script is called is as follows:

Bash +x example01.sh 5
2). Array, function pass-through number, loop

The following example shows the basic use of arrays, functions, loops, and so on.

#!/bin/bashif [[$#-lt 1]]; Thenecho "args count must > 1" echo "Uage:bash +x example01.sh [args ...]" Exitfi[email protected]for arg in $args; Doecho $argdonefunction Fun () {echo $1}fun "Hello Shell" fun2 () {echo "Linux"}fun2
Note that the function fun in the $ $. Gets the function parameters, not the parameters that were passed in when the script was called.

[Email protected] is the list of references passed in when a script call is obtained.

3). Use of the while loop and several other loops, case, and expression expr

#!/bin/bashif [[$#-lt 1]]; Then        echo "args count must > 1"        echo "Uage:bash +x example01.sh [args ...]"        Exitficase "        Install")                echo "Operation type is install"        ;;        " Uninstall ")                echo" Operation type is uninstall "        ;;        *)                echo "Operation type isn't support"        ;; Esacfor ((i=0;i<3;i++)) do        if ((i==1))        then                continue        fi        echo $idonefor i in ' seq 5 ' do        echo "Loop $i" done

Note that the case * is not all, but the input value is not in the case. Equivalent to default. It is possible to use continue/break and other keyword in the loop, very similar to other languages such as Java.

4). Script references to each other

Through source or. can refer to a function or variable in another script.

first.sh

function Fun () {echo ' I am from first.} File=first
second.sh

. First.shfunecho $file

Run with bash +x second.sh, you can call the fun function and use the file variable in second.sh.

Here the. and source are able to implement variables in the reference first file.Note: Consider a variable that references the same variable name for multiple scripts at the same time. The values that follow will overwrite the previous variables without error.

5). About Error Handling

A) is there a variable $ in the shell?

。 This variable records the result of the last script run. Assuming the normal end is 0, otherwise the value is 0.

b) Assume that the Set-o errexit in the shell script to exit when an error is encountered, which avoids many other errors;

c) Assuming an error during shell operation, can be redirected to output to a file, such as Command >> filename2>&1

6). Dictionary

The dictionary in the shell is a very good data structure, and it is very easy to handle the configuration

#!/bin/bashset-o Errexithput () {eval "hkey_$1" = "$ $"}hget () {eval echo ' ${' "hkey_$1" '} '}hput k1 v1hget k1declare-a dicdic = ([key1]= "value1" [key2]= "value2" [key3]= "Value3") echo ${dic["Key1"]}# output all Keyecho ${!dic[*]} #outpull All Valueecho ${dic[*]}# Access Allfor key in $ (echo ${!dic[*]}) does        echo "$key: ${dic[$key]}" done
After running, the output is as follows:

V1value1key3 Key2 key1value3 value2 value1key3:value3key2:value2key1:value1
7). Text Processing

The SED command is able to manipulate the text.

For example, there is a file sedfile, content such as the following:

12345
Running the sed ' 1,3d ' sedfile will output 4. 52 lines, that is, to do the removal of the line. Attentionthe two lines were not deleted in the file.。

In addition to deleting, you can also do a substitution operation.

[Email protected]:~/codelab# sed ' s/1/0/g ' sedfile 02345[email protected]:~/codelab# cat Sedfile 12345
We found that at the time of the output. Replace 1 with 0;

Another very powerful tool for text processing-awk

Let's first look at the basic processing of awk-get the text you want by cutting it with a comma (,).

Here we can see that awk can cut text in random form. then output;

8). Special variables and values

The following variables usually have a fixed meaning

$#    represents the number of variables. Often used to cycle [email protected]    all the parameters of the current command line.

Placed in a double-argument, indicating that the individual arguments $* the current command line. Placed in a double-lead. Indicates that the command line has all the parameters of a single $-(hyphen) in the reference number given to the shell option $?

Represents the status of the last command exit $$ indicates that the current process number, the current program name, is $! Represents the process number of a recent background command $home represents the current user root folder $ifs represents the internal field delimiter $lang the current locale default name $path environment variable $ppid parent process number $ PWD Current working folder

The following special values can help troubleshoot problems

0    Successful exit >0    exit failed 1-125    command exit failed, the related value returned by the failure is defined by the program (for example, exit in program only runs Exit 2. is returned as 2) the 126    command found but could not run the 127    command could not find the >128    command was killed by a signal
9. Scheduled Tasks

There are scheduled tasks under Windows System. There are also scheduled tasks on Linux systems. It can be realized by using the crontab of the system itself;

The output of Cat/etc/crontab running on my system is as follows:

[Email protected]:~/codelab# cat/etc/crontab #/etc/crontab:system-wide crontab# Unlike any other crontab you don ' t have To run the ' crontab ' # command to install the new version when you edit this file# and files in/etc/cron.d. These files also has username fields,# that none of the other crontabs does. shell=/bin/shpath=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin# m H Dom Mon Dow usercommand17 * * * Root    CD/&& run-parts--report/etc/cron.hourly25 6* * *roottest-x/usr/sbin/anacron | | (CD/&& run-parts--report/etc/cron.daily) 6* * 7roottest-x/usr/sbin/anacron | | (CD/&& run-parts--report/etc/cron.weekly) * *roottest-x/usr/sbin/anacron | | (CD/&& run-parts--report/etc/cron.monthly) #
From here we can see how cron is used, where Cron uses the shell, and here's how the command is set up.

Minute: Represents minutes, which can be from 0 to 59 regardless of the integer. Hour: Represents the hour, which can be any integer from 0 to 23.

Day: Represents the date. can be from 1 to 31 regardless of the integer. Month: Represents the months. can be from 1 to 12 regardless of the integer.

Week: Represents the day of the week, can be from 0 to 7 regardless of what integer, here the 0 or 7 stands for Sunday. Command: Commands to run, can be system commands, can also be written by their own script files.

We are able to use some basic commands such as the following;

Usage:crontab [-u user] filecrontab [-u user] [-i] {-e |-l |-r} (default operation is replace, per 1003.2)-E (Edit u Ser ' s crontab)-L (list user ' s crontab)-R (delete user's crontab)-I (Prompt before deleting user's crontab)
10). Tips

A) infer if the parameter is a number.

#!/bin/sh#1. $ $ is the first parameter of the script, which is passed to the awk command as the first parameter of the awk command. #2. Because there is no input file as the input stream. So this is just the completion of the Begin block.

#3. In awk, the ARGV array represents an array of parameters for the awk command, Argv[0] represents the command itself, and Argv[1] represents the first number of parameters.

#4. Match is the built-in function of awk, and the return value is the starting position of the matching regular table in the string (Argv[1]). No return 0 found. #5. The notation of the form has ensured that the matching string must be a positive integer in decimal, such as a floating-point number or a negative number, only need to change the regular. #6. When awk finishes running, it returns the result to the ISDIGIT variable as its initialization value.

#7. Isdigit= ' echo $ | awk ' {if (Match ($, "^[0-9]+$")! = 0) print "true"; else print "false"} ' #8. The above notation can also be implemented, but because there are multiple processes involved, the efficiency is lower than the following notation. isdigit= ' awk ' BEGIN {if (Match (argv[1], "^[0-9]+$")! = 0) print "true"; else print "false"} ' if [[$isdigit = = ' true ' ]]; Then echo "This is numeric variable." Number=$1

Fi
b) Assign values to variables based on system to ensure portability
#1. Gets the current system name through the uname command. Then, depending on the OS name, the ping variable is assigned the full name of a different ping command.

Osname= ' Uname-s ' #2. Can include many other 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

3. Summary

These are just the most basic parts of shell development. Shell is in fact a very efficient and powerful language, constantly learning and accumulation will become more and more skilled.









Linux Shell Usage Notes

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.