Shell script programming under Linux 1

Source: Internet
Author: User



1. What is a shell script?



It is a scripting language, not a programming language.



You can use some logical judgments, loops, and other syntax.



You can customize the sub-function, which is a collection of system commands.



Shell scripts enable automated operations, which greatly increase our productivity.






2. Shell script structure and execution method



Start line Specify Bash path: #! /bin/bash



Lines that begin with # are interpreted as explanatory notes



#Annotate your script content for easy access; UTF8 character set, support Chinese;



The name of the script ends with. SH and is used to differentiate between this is a shell script



There are two ways to execute a script:



chmod a+x 1.sh add x Execute permission;



./1.sh can execute directly, or write absolute path/root/shell/1.sh



If no execute permission can bash 1.sh or sh 1.sh



Bash-x 1.sh To view the script execution process



Lab Exercises:


[[email protected] shell] # cat 1.sh
#! / bin / bash
#This is my first script
echo "hello world"
[[email protected] shell] # ls -l
-rw-r--r-- 1 root root 60 June 16 19:28 1.sh
[[email protected] shell] # chmod a + x 1.sh
[[email protected] shell] # ls -l
-rwxr-xr-x 1 root root 60 June 16 19:28 1.sh
[[email protected] shell] # ./1.sh
hello world
[[email protected] shell] # /root/shell/1.sh
hello world
[[email protected] shell] # / bin / sh 1.sh
hello world
[[email protected] shell] # bash -x 1.sh
+ echo ‘hello world’
hello world





Execution bash and SH are the same, SH is a soft connection file for bash;


[[email protected] ~]# ls -l /bin/bash 
-rwxr-xr-x. 1 root root 871700 10月 16 2014 /bin/bash
[[email protected] ~]# ls -l /bin/sh
lrwxrwxrwx. 1 root root 4 3月   4 00:59 /bin/sh -> bash




3, learn the use of the date command



Date +%y-%m-%d date +%y-%m-%d Month Day



Date +%y-%m-%d = Date +%f Month Day



Date +%h:%m:%s = Date +%t time



Date +%s Timestamp



Date-d @1434248742 calculates the current time based on time stamp



Date-d "+1day" a day later date-d " -1day" a day ago



Date-d " -1month" month ago



Date-d " -1min" a minute ago



Date +%w Date +%w week






Lab Exercises:


[[email protected] shell]# date +%y
15
[[email protected] shell]# date +%Y
2015
[[email protected] shell]# date +%m
06
[[email protected] shell]# date +%d
16
[[email protected] shell]# date +%H
14
[[email protected] shell]# date +%M
01
[[email protected] shell]# date +%S
54


How many seconds are counted from 0:0 on January 01, 1970;


[[email protected] shell] # date +% s
1434434874
[[email protected] shell] # date -d @ 1434434874
Tuesday, June 16, 2015 14:07:54 CST


CST is China time + 8 hours


[[email protected] shell] # date -d @ 0
Thursday, January 01, 1970 08:00:00 CST


[[email protected] shell] # date +% F
2015-06-16
[[email protected] shell] # date +% T
14:04:17
[[email protected] shell] # date +% Y-% m-% d
2015-06-16
[[email protected] shell] # date + "% Y-% m-% d% H:% M:% S"
2015-06-16 14:05:13
[[email protected] shell] # date + "% F% T"
2015-06-16 14:05:38


Tuesday


[Email protected] shell]# date +%w2


How many weeks, 24 weeks of this year


[Email protected] shell]# date +%w24


How many weeks and 52 weeks are available throughout the year;


[Email protected] shell]# echo "365/7" | Bc52
[[email protected] shell] # date -d "-1 day"
Monday, June 15, 2015 14:16:31 CST
[[email protected] shell] # date -d "-1 day" + "% F% T"
2015-06-15 14:19:13
[[email protected] shell] # date -d "+1 day" + "% F% T"
2015-06-17 14:19:22
[[email protected] shell] # date -d "+1 month" + "% F% T"
2015-07-16 14:19:31
[[email protected] shell] # date -d "+1 year" + "% F% T"
2016-06-16 14:19:39
[[email protected] shell] # date -d "+1 week" + "% F% T"
2015-06-23 14:19:45
[[email protected] shell] # date -d "-10 hour" + "% F% T"
2015-06-16 04:19:59
[[email protected] shell] # date -d "-10 min" + "% F% T"
2015-06-16 14:10:15
[[email protected] shell] # date -d "-10 sec" + "% F% T"
2015-06-16 14:20:14





4. Variables in shell scripts



You should use a variable instead when you use a string more frequently in your script and the string length is long.



When using conditional statements, the variable if [$a-gt 1] is often used; Then ...; Fi



Replace n= ' Wc-l 1.txt ' with a variable when referencing the result of a command



When writing and user interaction scripts, variables are also essential for read-p "Input a number:" N; Echo $n



If you do not write this n, you can use $reply directly



Built-in variables, $ $, $2,$# $ $ represents the script itself, the first argument, the $ two argument, $ #表示参数的个数;



Mathematical Operation a=1;b=2; c=$ (($a + $b)) or c=$[$a + $b]






Lab Exercises:



Referencing the result of a command, using a variable instead


[[email protected] shell]# file=`which yum`
[[email protected] shell]# echo $file
/usr/bin/yum
[[email protected] shell]# rpm -qf $file
yum-3.2.29-60.el6.centos.noarch


The variable only takes effect under the current shell, and the child shell does not take effect;



To make the child shell effective, declare the variable using export file;



Variables for user interaction:


[[email protected] shell] # cat 2.sh
#! / bin / bash
#Variables interacting with the user
read -p "Please enter a number:" num
echo $ num
[[email protected] shell] # sh 2.sh
Please enter a number: 333
333


Variables for parameters:


[[email protected] shell] # cat 3.sh
#! / bin / bash
#About parameter variables
echo "\ $ 1 = $ 1"
echo "\ $ 2 = $ 2"
echo "\ $ 3 = $ 3"
echo "\ $ # = $ #"
echo "\ $ 0 = $ 0"
[[email protected] shell] # sh 3.sh ABC linux world
$ 1 = ABC
$ 2 = linux
$ 3 = world
$ # = 3
$ 0 = 3.sh


Numeric variables:


[[email protected] shell] # a = 1; b = 2
[[email protected] shell] # c = $ a + $ b
[[email protected] shell] # echo $ c
1 + 2
[[email protected] shell] # c = $ [$ a + $ b]
[[email protected] shell] # echo $ c
3
[[email protected] shell] # c = $ (($ a + $ b))
[[email protected] shell] # echo $ c
3





5. Logic judgment in the shell



Format 1:if condition; Then statement; Fi



Format 2:if condition; Then statement; else statement; Fi



Format 3:if ...; Then ...; Elif ...; Then ...; else ...; Fi



Logical judgment expression: if [$a-gt $b]; If [$a-lt 5]; If [$b-eq 10] etc.; Notice that there are spaces everywhere.



can use && and | | or combine multiple conditions



Greater than >gt (greater than)



Smaller than < LT (lessthan)



Greater than or equal to >= ge



Less than or equal to <= le



equals ==eq (equal)



Not equal to! = NE



Lab Exercises:


[[email protected] shell] # cat if.sh
#! / bin / bash
#if judgment statement, the condition is true, print true;
if:
then
     echo true
fi
[[email protected] shell] # sh if.sh
true


if Judgment Statement 2;


[[email protected] shell] # cat if2.sh
#! / bin / bash
#if judgment statement, the condition is true, return true;
if [1 == 1]
then
echo "true"
fi
[[email protected] shell] # sh -x if2.sh
+ ‘[‘ 1 == 1 ‘]’
+ echo true
true
[[email protected] shell] # sh if2.sh
true


If Judgment Statement 3;


[[email protected] shell] # cat if3.sh
#! / bin / bash
#if statement, if the condition is true, return true, if the condition is false, return false;
if ["1" == "2"]
then
echo "true"
else
echo "false"
fi
[[email protected] shell] # sh if3.sh
false


variables, compare them


[[email protected] shell] # cat if4.sh
#! / bin / bash
#if judgment statement, variables are compared;
a = 1
if ["$ a" == "2"]
then
echo "true"
else
echo "false"
fi
[[email protected] shell] # sh -x if4.sh
+ a = 1
+ ‘[‘ 1 == 2 ‘]’
+ echo false
false


Multiple judgments to add elif


[[email protected] shell] # cat if5.sh
#! / bin / bash
#if judgment statement, multiple judgments use elif;
a = 1
if ["$ a" == "2"]
then
echo "true"
elif ["$ a" -lt 10]
then
echo "no false"
else
echo "false"
fi
[[email protected] shell] # sh if5.sh
no false


[$a-LT 3] can also be substituted (($a <3)); Use square brackets please pay attention to the space;


[[email protected] shell]# a=1;if(($a<3)); then echo OK;fi
OK
[[email protected] shell]# a=1;if [ $a -lt 3 ]; then echo OK;fi
OK


&& the previous execution is successful before the following is executed;



|| Or the preceding execution is unsuccessful in performing the following;


[[email protected] shell]# a=5
[[email protected] shell]# if [ $a -lt 10 ]&&[ $a -gt 2 ];then echo OK;fi
OK
[[email protected] shell]# if [ $a -lt 10 ]||[ $a -gt 2 ];then echo OK;fi
OK





Odd even judgment, the input number divided by 2, the remainder of 0 is even, not 0 is odd;


[[email protected] shell] # cat 4.sh
#! / bin / bash
read -p "enter a number:" n
n1 = $ [$ n% 2]
if [$ n1 -eq 0]
then
echo "The number you entered is even"
else
echo "The number you entered is odd"
fi
[[email protected] shell] # sh 4.sh
enter a number: 23
The number you entered is odd
[[email protected] shell] # sh 4.sh
enter a number: 90
The number you entered is even


Judge whether the input is a number, not a direct exit of the number, or an odd or even number;



' Echo $n |grep-c ' [^0-9] ' matches the input character as a non-numeric line number if the 1 description is not a number.


[[email protected] shell] # cat 5.sh
#! / bin / bash
#Determine if the input is a number, not directly exit the number; if the number is judged, it is odd or even
read -p "Please enter a number:" n
n2 = `echo $ n | grep -c‘ [^ 0-9] ‘`
if [$ n2 -eq 1]
then
echo "You did not enter a pure number, please enter it again"
exit 1
fi
n1 = $ [$ n% 2]
if [$ n1 -eq 0]
then
echo "The number you entered is even"
else
echo "The number you entered is odd"
fi

[[email protected] shell] # sh 5.sh
Please enter a number: abc
You did not enter a pure number, please re-enter
[[email protected] shell] # sh 5.sh
Please enter a number: 323
The number you entered is odd


6. If judgment file, directory attribute



[-F file] Determines if it is a normal file, and there is



[-D file] Determines if it is a directory and exists



[-E file] to determine whether files or directories exist



[-R File] to determine if the document is readable



[-W file] Determines whether the file is writable



[-X file] Determines whether the file is executable



Lab Exercises:



1.SH exists then executes the following


[[Email protected] shell]# [-F 1.sh] && echo "1.sh exist" 1.sh exist


21.sh does not exist behind the execution.


[[Email protected] shell]# [-f 21.sh] | | Echo ' 1.sh not exist ' 1.sh not exist


Determine if a file exists


[[email protected] shell] # cat test.sh
#! / bin / bash
# Determine if 1.sh exists;
if [-e 1.sh]
then
echo "1.sh exist"
else
echo "1.sh not exist"
fi
[[email protected] shell] # sh test.sh
1.sh exist





The use of exec, combined with the date variable experiment



The EXEC command is used to invoke and execute instructions. The EXEC command is typically used in shell scripting programs to invoke other commands. If the command is used in the current terminal, the terminal is exited immediately when the specified command finishes executing.


[[email protected] shell] # cat date.sh
#! / bin / bash
#exec usage, combined with the date variable experiment;
d = `date +% F`
exec> /tmp/$d.log 2> & 1
echo "Begin at` date` "
ls / tmp / abc
cd / ddd
echo "End at` date` "
[[email protected] shell] # sh date.sh
[[email protected] shell] # cat /tmp/2015-06-16.log
Begin at Tuesday June 16, 2015 16:49:54 CST
ls: inaccessible / tmp / abc: no such file or directory
date.sh: line 7: cd: / ddd: no such file or directory
End at Tuesday June 16, 2015 16:49:54 CST 


EXEC >/tmp/$d. Log 2>&1 means that the following line is executed, and the output of the correct or incorrect information is written to the date in the/tmp/directory. log inside;






This article is from the "Model Student's Learning blog" blog, please be sure to keep this source http://8802265.blog.51cto.com/8792265/1662833



Shell script programming under Linux 1


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.