shell知识点整理

来源:互联网 发布:韩语入门软件 编辑:程序博客网 时间:2024/06/07 18:40

转载:http://blog.csdn.net/zjf280441589/article/details/39667929


简单的示例Shell程序

示例1.

[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #!/bin/bash  
  2. #This is to show what a shell script looks like  
  3. echo "Our first example"  
  4. echo # This inserts an empty line in output.  
  5. echo "We are currently in the following directory."  
  6. /bin/pwd  
  7. echo  
  8. echo "This directory contains the following files"  
  9. /bin/ls -l .  

示例2.

[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #!/bin/bash  
  2. # Auto mail for system info  
  3.   
  4. /bin/date +%F >> /tmp/sysinfo  
  5. echo >> /tmp/sysinfo  
  6.   
  7. echo "Disk info:" >> /tmp/sysinfo  
  8. /bin/df -h >> /tmp/sysinfo  
  9. echo >> /tmp/sysinfo  
  10.   
  11. echo "Online users:" >> /tmp/sysinfo  
  12. /usr/bin/who | /bin/grep -v root >> /tmp/sysinfo  
  13. echo >> /tmp/sysinfo  
  14.   
  15. echo "Memory info:" >> /tmp/sysinfo  
  16. /usr/bin/free -m >> /tmp/sysinfo  
  17. echo >> /tmp/sysinfo  
  18.   
  19. # Write to root   
  20. /usr/bin/write root < /tmp/sysinfo && /bin/rm -f /tmp/sysinfo  
  21.   
  22. # crontab -e  
  23. # 0 9 * * 1-5 ./sysinfo.sh  




Shell结构

1#!指定执行脚本的Shell

2#注释行,描述该脚本的作用,负责人等信息

3、命令和控制结构

 

创建shell程序的步骤

第一步:创建一个包含命令和控制结构的文件。 

第二步:修改这个文件的权限使它可以执行: chmod u+x 

第三步:执行 ./example 或 sh example 或 . sysinfo.sh

  

Shell变量

变量:shell传递数据的一种方法,用来代表每个取值的符号名。 

Shell有两类变量:临时变量永久变量。 

临时变量是shell程序内部定义的,其使用范围仅限于定义它的程序,对其它程序不可见。包括:用户自定义变量、位置变量。

永久变量是环境变量,其值不随shell脚本的执行结束而消失。

 

1、用户自定义变量

用户定义的变量由字母或下划线开头,由字母、数字或下划线序列组成,区分大小写。变量名长度没有限制。在使用变量值,要在变量名前加上前缀“$” 

 

2、设置和使用变量

设置变量:习惯上用大写字母来命名变量。变量名只能以字母表中的字符开头,不能用数字。 

变量赋值:=”两边没有空格。 

定义时赋值,NUM=1 

将一个命令的执行结果赋给变量,:TIME=`date`;TIME=$(date +%F)

将一个变量的值赋给另一个变量,:B=120 ; A =$B 

使用echo命令查看变量值。例如:echo $A 

 

3、包含多个字的变量

NAME=Mike Ron #运行时出错,应改为:

NAME=“Mike Ron” 或 $NAME=‘Mike Ron’ 

 

4、单引号与双引号的区别

比如:定义DATE=$(date +%F)

time=”time is $DATE”

echo $time

time='time is $DATE'

echo $time

 

单引号之间的内容原封不动地指定给了变量。 

 

5 set查看系统中定义的所有变量

unset删除所定义的变量

 

6、位置变量

Shell解释执行用户命令时,将命令行的第一个部分作为命令名,其它部分作为参数。由出现在命令行上的位置确定的参数称为位置参数。 

例如

ls -l file1 file2 file3 

$0 这个程序的文件名 ls -l 

$n 这个程序的第n个参数值,n=1~9 

 

7、特殊变量

$* 这个程序的所有参数 

$# 这个程序的参数个数 

$$ 这个程序的PID 

$! 执行上一个后台命令的PID 

$? 执行上一个命令的返回值

 

 

示例-autobak.sh

[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #!/bin/bash  
  2. # backup files by date  
  3.   
  4. DATE=$(/bin/date +%Y%m%d)  
  5. /bin/tar -cf /backup/$1.$DATE.tar $1 > /dev/null 2>> /backup/$1.bak.log  
  6. /bin/gzip  /backup/$1.$DATE.tar  
  7.   
  8. if [ $? -eq 0 ]   
  9. then  
  10.     echo "$1 $DATE backup successfully" >> /backup/$1.bak.log  
  11. else  
  12.     echo "ERROR: failure $1 $DATE backup" >> /bakup/$1.bak.log  
  13. fi  
  14.   
  15. # crontable -e  
  16. # 0 3 * * 2,5 script  

 

示例-special.sh

[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #!/bin/bash  
  2. # A test script for special var  
  3.   
  4. echo '$# is' $#  
  5. echo '$* is' $*  
  6. echo '$0 is' $0  
  7. echo '$? is' $?  
  8. echo '$$ is' $$  
  9. echo '$2 is' $2  

Shell命令

1read命令[交互方式]

read USERNAME

示例-read.sh

[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #!/bin/bash  
  2. # A test script for read  
  3.   
  4. read first second third  
  5.   
  6. echo "Your first parameter is $first"  
  7. echo "Your second parameter is $second"  
  8. echo "Your third parameter is $third"  

#sh -x 命令:单步调试显示执行

 

 

2expr命令,对整型变量进行运算

如: expr 3 + 5  #”+”号之间须有空格

expr $var1 - 5 

expr $var1 / $var2 

expr $var3 \* 10  #”*”号需要转义符”\”

 

 

复杂的运算

expr `expr 5 + 7`/$var4

 

将运算结果赋予变量

var4=` expr $var1 / $var2 ` 

 

示例-expr.sh

[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #!/bin/bash  
  2. # A test for expr  
  3.   
  4. a=10  
  5. b=20  
  6. c=30  
  7.   
  8. val1=$(expr $a + $b + $c)  
  9. echo "The value of val1 is $val1"  
  10. val2=$(expr $c / $b)  
  11. echo "The value of val2 is $val2"  
  12. val3=`expr $a \* $b`  
  13. echo "The value of val3 is $val3"  
  14. val4=`expr $a + $c / $b`  
  15. echo 'The value of $a + $c / $b is ' $val4  

变量测试语句-test

作用:用来测试变量是否相等,是否为空,文件类型等。

格式:

test 测试条件 或 [] #范围:整数,字符串,文件  

 

1)整数测试

test int1 -eq int2  测试整数是否相等 

test int1 -ge int2  测试int1是否>=int2 

test int1 -gt int2  测试int1是否>int2 

test int1 -le  int2 测试int1是否<=int2 

test int1 -lt int2  测试int1是否<int2 

test int1 -ne int2  测试整数是否不相等

 

2)字符串测试

test str1=str2  测试字符串是否相等 

test str1!=str2  测试字符串是否不相等 

test str1  测试字符串是否不为空 

test -n str1  测试字符串是否不为空 

test -z str1  测试字符串是否为空

 

3)文件测试

test -d file  指定文件是否目录 

test -f file  指定文件是否常规文件 

test -x file  指定文件是否可执行 

test -r file  指定文件是否可读 

test -w file  指定文件是否可写 

test -a file 指定文件是否存在 

test -s file 文件的大小是否非0

 

注:test测试语句一般不单独使用,一般作为if语句的测试条件,;

[python] view plain copy
  1. if test -d file  
  2. then  
  3.     ....  
  4. fi  


 

test的变量的简写形式”[]”

 

示例-apachtest.sh

[python] view plain copy
  1. #!/bin/bash  
  2. # A test shell script for test Apache is running or not  
  3.   
  4. web=$(/usr/bin/pgrep httpd)  
  5.   
  6. echo "Now let's test the Apache..."  
  7. echo  
  8.   
  9. #if [ "$web" != "" ]  
  10. if [ -n "$web" ]  
  11. then  
  12.     echo "Apache is running..."  
  13. else  
  14.     echo "Apache is NOT running..."  
  15.     /etc/rc.d/init.d/httpd start  
  16. fi  

流程控制语句

流控制语句:用于控制shell程序的流程 

exit语句:退出程序执行,并返回一个返回码,返回码为0表示正常退出,0表示非正常退出。 

例如:exit 0 

 

一、if

if/then格式

[python] view plain copy
  1. if test -d $1   
  2. then   
  3.         ...   
  4. fi   

示例-if_then.sh

[python] view plain copy
  1. #!/bin/bash  
  2. # A test shell script for if/then  
  3.   
  4. if [ -x /etc/rc.d/init.d/httpd ]  
  5. then  
  6.     echo "Script: /etc/rc.d/init.d/httdp have x power!"  
  7.     /etc/rc.d/init.d/httpd restart  
  8. fi  

if/else格式

[python] view plain copy
  1. if 条件1   
  2. then   
  3.     命令1   
  4. elif 条件2  
  5. then   
  6.     命令2   
  7. else   
  8.     命令3   
  9. fi   

多个条件的联合

-a: 逻辑与,仅当两个条件都成立时,结果为真。 

-o: 逻辑或,两个条件只要有一个成立,结果为真。

 

示例-if_else.sh

[python] view plain copy
  1. #!/bin/bash  
  2. # A test shell script for if/elif/else  
  3.   
  4. echo -n "Please input a filename: "  
  5. read filename  
  6.   
  7. if [ -d $filename ]  
  8. then  
  9.     echo "$filename is a directory"  
  10. elif [ -f $filename ]  
  11. then  
  12.     echo "$filename is a commen file"  
  13. elif [ -c $filename -o -b $filename ]  
  14. then  
  15.     echo "$filename is a device file"  
  16. else  
  17.     echo "$filename is a unkown file"  
  18. fi  

 

示例-if_elif_exit.sh

[python] view plain copy
  1. #!/bin/bash  
  2. # A test shell script for if/elif  
  3.   
  4. if [ $# -ne 2 ]   
  5. then  
  6. echo "Not enough parameters"  
  7. exit 1  
  8. fi  
  9.   
  10. if [ $1 -gt $2 ]  
  11. then  
  12.     echo "$1 is great then $2"  
  13. elif [ $1 -lt $2 ]  
  14. then  
  15.     echo "$1 is little then $2"  
  16. else  
  17.     echo "$1 is equal as $2"  
  18. fi  

二、for/in

[python] view plain copy
  1. for 变量 in 名字表   
  2. do   
  3.     命令列表   
  4. done   

示例-for.sh

[python] view plain copy
  1. #!/bin/bash  
  2. # A test shell script for "for"  
  3.   
  4. for DAY in Sunday Monday Tuesday Wednesday Thursday Friday Saturday  
  5. do  
  6.     echo "The day is $DAY"  
  7. done  


awk命令[分段提取]

awk -F域分隔符 命令[单引号] #如果不用-F指定分割符,默认为空格

 

1、检测系统中UID0的用户 

awk -F: '$3==0 {print $1}' /etc/passwd

#awk -F: '{print $1}' /etc/passwd

-F 指定分割附为:

$3 表示以:为分割附的第三位

 

2、检测系统中密码为空的用户 

awk -F: 'length($2)==0 {print $1}' /etc/shadow 

#ps aux | grep -v root | awk '{print $2}'

示例-awk.sh

[python] view plain copy
  1. #!/bin/bash  
  2. # A test script for desplay users infomation  
  3.   
  4. /bin/echo -n "Please input a username: "  
  5. read username  
  6.   
  7. /bin/grep $username /etc/passwd > /dev/null 2> /dev/null  
  8.   
  9. if [ $? -eq 0 ]  
  10. then  
  11.     /bin/echo "username is: $username"  
  12. else  
  13.     /bin/echo "user: $username is not exits."  
  14.     exit 1  
  15. fi  
  16. /bin/echo  
  17.   
  18. # list /etc/passwd info  
  19. userinfo=`/bin/grep ^$username:x /etc/passwd`  
  20. uid=`echo $userinfo | awk -F: '{print $3}'`  
  21. gid=`echo $userinfo | awk -F: '{print $4'}`  
  22. dir=`echo $userinfo | awk -F: '{print $6}'`  
  23. shell=`echo $userinfo | awk -F: '{print $7}'`  
  24.   
  25. # get /etc/group info  
  26. groupinfo=`/bin/grep x:$gid /etc/group`  
  27. gname=`/bin/echo $groupinfo | awk -F: '{print $1}'`  
  28.   
  29. /bin/echo "user id is: $uid"  
  30. /bin/echo "default group is: $gname"  
  31. /bin/echo "home directory is: $dir"  
  32. /bin/echo "shell is: $shell"  
  33. /bin/echo "group member info:"  
  34.   
  35. # get group members  
  36. groups=`/usr/bin/groups $username`  
  37. /bin/echo $groups  
  38. /bin/echo  
  39.   
  40. # get online info  
  41. online=`/usr/bin/who | grep $username`  
  42. if [ -z "$online" ]  
  43. then  
  44.     echo "$username is not online"  
  45. else  
  46.     echo "$username is online..."  
  47. fi  

 

实例-killuser.sh

[python] view plain copy
  1. #思路:将一个用户所有的进程包括shell都关闭,则相当于将该用户踢出了系统  
  2. #!/bin/bash  
  3. # A shell sript to kill a user in Linux  
  4.   
  5. username=$1  
  6.   
  7. killpid=`/bin/ps aux | grep $username | awk '{print $2}'`  
  8.   
  9. for PID in $killpid  
  10. do  
  11.     /bin/kill -9 $PID 2> /dev/null  
  12. done  

流程控制语句

三、select/in[较少用]

格式:

[python] view plaincopy
  1.     select [变量] in [关键字]  
  2.     do   
  3.         command 1   
  4.         ... ...   
  5.         command n   
  6.     done   
  7. #select把关键字中的每一项做成类似表单,以交互的方式执行do和done之间的命令  

示例-select.sh

[python] view plaincopy
  1. #!/bin/bash  
  2. # Show select usage  
  3.   
  4. echo "What's your favorate OS?"  
  5.   
  6. select var in "Linux" "Windows" "UNIX" "Other"  
  7. do  
  8.     break  
  9. done  
  10.   
  11. echo "You have selected $var"  



四、case/esac

格式:

[python] view plaincopy
  1. case 变量 in   
  2. 字符串1)   
  3.     命令列表1   
  4.     ;;   
  5.     ...   
  6. 字符串n)   
  7.     命令列表n   
  8.     ;;   
  9. esac  

示例-case.sh

[python] view plaincopy
  1. #!/bin/bash  
  2. # Show Usage for case/esac  
  3.   
  4. echo "*********************************"  
  5. echo "Please select a oprator as below:"  
  6. echo "C ... copy"  
  7. echo "D ... delete"  
  8. echo "B ... backup"  
  9. echo "*********************************"  
  10.   
  11. read op  
  12. case $op in  
  13.     C)    
  14.         echo "copy...."  
  15.         ;;    
  16.     D)    
  17.         echo "delete...."  
  18.         ;;    
  19.     B)    
  20.         echo "backup..."  
  21.         ;;  
  22.     *)  
  23.         echo "Unknow operator!"  
  24.         exit 1  
  25. esac  

示例-select.case

[python] view plaincopy
  1. #!/bin/bash  
  2. # A test shell script for select and case  
  3.   
  4. echo "a is 5, b is 3, please select your method"  
  5. a=5  
  6. b=3;  
  7.   
  8. select var in "a+b" "a-b" "a*b" "a/b"  
  9. do  
  10.     break  
  11. done  
  12.   
  13. case $var in  
  14.     "a+b")  
  15.         echo "a+b="`expr $a + $b `  
  16.         ;;    
  17.     "a-b")  
  18.         echo "a-b="`expr $a - $b`  
  19.         ;;    
  20.     "a*b")  
  21.         echo "a*b="`expr $a \* $b`  
  22.         ;;  
  23.     "a/b")  
  24.         echo "a/b="`expr $a / $b`  
  25.         ;;  
  26.     *)  
  27.         echo "input error..."  
  28.         exit 1  
  29. esac  

实例-/etc/rc.d/init.d/httpd部分源代码

[python] view plaincopy
  1. # See how we were called.  
  2. case "$1" in  
  3.   start)  
  4.     start  
  5.     ;;  
  6.   stop)  
  7.     stop  
  8.     ;;  
  9.   status)  
  10.     ;;  
  11.   restart)  
  12.     stop  
  13.     start  
  14.     ;;    
  15.   condrestart|try-restart)  
  16.     if status -p ${pidfile} $httpd >&/dev/null; then  
  17.         stop  
  18.         start  
  19.     fi  
  20.     ;;  
  21.   force-reload|reload)  
  22.         reload  
  23.     ;;  
  24.   graceful|help|configtest|fullstatus)  
  25.     $apachectl $@  
  26.     RETVAL=$?  
  27.     ;;  
  28.   *)  
  29.     echo $"Usage: $prog {start|stop|restart|condrestart|try-restart|force-reload|reload|status|fullstatus|graceful|help|configtest}"  
  30.     RETVAL=2  
  31. esac  



五、while

格式:

[python] view plaincopy
  1. while 条件    #无限:while true  
  2. do   
  3.     命令   
  4. done   

示例-while.sh

[python] view plaincopy
  1. #!/bin/bash  
  2. # A usage for while  
  3.   
  4. num=1  
  5. while [ $num -le 10 ]  
  6. do  
  7.     echo $(expr $num \* $num)  
  8.     let num++  
  9. done  

示例-useradd.sh

[python] view plaincopy
  1. #!/bin/bash  
  2. # A shell script to add user(s)  
  3. #echo 123456 | passwd --stdin xiaofang  #用非交互方式设置xiaofang的密码  
  4.   
  5. echo -n "Plese input the user name: "  
  6. read username  
  7. echo -n "Plese input the sum users: "  
  8. read sum  
  9.   
  10. num=1  
  11. while [ $num -le $sum ]  
  12. do  
  13.     /usr/sbin/useradd "$username$num"     
  14.     if [ $? -ne 0 ]   
  15.     then  
  16.         echo "user: $username already exists."  
  17.         exit 1  
  18.     fi    
  19.       
  20.     let num++  
  21. done  
  22.   
  23. echo -n "Please input the passwd for this users: "  
  24. read passwd  
  25.   
  26. i=1  
  27. while [ $i -le $sum ]  
  28. do  
  29.     echo $passwd | /usr/bin/passwd --stdin "$username$i"  
  30.     let i++  
  31. done  




示例-userdel.sh

[python] view plaincopy
  1. #!/bin/bash  
  2. # A shell script for delete user(s)  
  3.   
  4. echo -n "Please input the username: "  
  5. read username  
  6. echo -n "Please input the user number: "  
  7. read num   
  8.   
  9. i=1  
  10. while [ $i -le $num ]  
  11. do  
  12.     /usr/sbin/userdel -r $username$i  
  13.     if [ $? -ne 0 ]   
  14.     then  
  15.         echo "User: $username$i is not exists."  
  16.         let i++   
  17.         continue  
  18.     fi    
  19.   
  20.     let i++   
  21. done  

六、until

格式:

[python] view plaincopy
  1.     until 条件   
  2.     do   
  3.         命令   
  4.     done   
  5. #until类似while循环,不同的是until是条件返回值为假时才继续执行。  

示例-until.sh

[python] view plaincopy
  1. #!/bin/bash  
  2. # A script to show until usage.  
  3.   
  4. echo "Please input Y/y to stop..."  
  5. read input  
  6.   
  7. until [ "$input" = "Y" ] || [ "$input" = "y" ]  
  8. do  
  9.     echo "input error, input again!"  
  10.     read input  
  11. done  

七、跳出循环:breakcontinue 

break:跳出整个循环 

continue:跳过本次循环,进行下次循环

 

示例-break_continue.sh

[python] view plaincopy
  1. #!/bin/bash  
  2. # A test shell script for break&continue  
  3.   
  4. while true  
  5. do  
  6.     echo "*****************************"  
  7.     echo "Please have a select as blow:"  
  8.     echo "1 Copy"  
  9.     echo "2 Delete"  
  10.     echo "3 Backup"  
  11.     echo "4 Quit***********************"  
  12.     read op  
  13.   
  14.     case $op in  
  15.         "1")  
  16.             echo "$op is Copy"  
  17.             ;;    
  18.         "2")  
  19.             echo "$op is Delete"  
  20.             ;;    
  21.         "3")  
  22.             echo "$op is Backup"  
  23.             ;;  
  24.         "4")  
  25.             echo "Exit..."  
  26.             break  
  27.             ;;  
  28.         "*")  
  29.             echo "Invalide selectino, please select again..."  
  30.             continue  
  31.             ;;  
  32.     esac  
  33. done  

 

八、shift指令

参数左移,每执行一次,参数序列顺次左移一个位置,$#的值减1, 用于分别处理每个参数,移出去的参数不再可用

 

示例-shift.sh

[python] view plaincopy
  1. #!/bin/bash  
  2. # A test shell script for shift  
  3.   
  4. if [ $# -lt 1 ]   
  5. then  
  6.     echo "No enough parameters"  
  7.     exit 1  
  8. fi  
  9.   
  10. num=0  
  11. while [ $# -gt 0 ]   
  12. do  
  13.     echo '$1 is '$1  
  14.     let num++  
  15.     shift  
  16. done  
  17.   
  18. echo $num  

函数应用

实例-/etc/rc.d/init.d/httpd中的start源代码

 

一、函数的定义

[python] view plaincopy
  1. 函数名 ()   
  2. {   
  3.     命令序列   
  4. }   


二、函数的调用:不带() 

函数名 参数参数2 ... 参数n

实例-调用

 

 

三、函数中的变量

变量均为全局变量,没有局部变量

 

四、函数中的参数:

调用函数时,可以传递参数,在函数中用$1$2...来引用 

 

示例-function.sh

[python] view plaincopy
  1. #!/bin/bash  
  2. # A test shell script for function  
  3.   
  4. # function  
  5. Help(){  
  6.     echo "Usage: sh function \$1 \$2 \$3"  
  7. }  
  8.   
  9. Display(){  
  10.     echo "three argument: $1 $2 $3"  
  11. }  
  12.   
  13. # main  
  14. if [ $# -ne 3 ]   
  15. then  
  16.     Help  
  17. else  
  18.     echo "Think you for your input"  
  19.     Display $1 $2 $3  
  20. fi  

Shell 脚本调试 

sh -x script  这将执行该脚本并显示所有变量的值。 

sh -n script  不执行脚本只是检查语法的模式,将返回所有语法错误。 

 

最佳实践-命令最好使用绝对路径

 

一个脚本能够执行-

1.对脚本有rx权限,只有r,可以使用sh执行

2.对脚本所在目录至少有rx权限

 

拓展实例-setuid.sh

[python] view plaincopy
  1. #!/bin/bash  
  2. # After the system installed, please check setuid files first for security  
  3. # mkdir /backup  
  4. # find / -perm -4000 -o -perm -2000 > /backup/setuid.list  
  5.   
  6. /bin/find / -perm -4000 -o -perm -2000 > /tmp/setuid.list 2> /dev/null  
  7.   
  8. for var in `/bin/cat /tmp/setuid.list`  
  9. do  
  10.     /bin/grep $var /backup/setuid.list > /dev/null 2> /dev/null  
  11.     if [ $? -ne 0 ]   
  12.     then  
  13.         echo "$var is not in /backup/setuid.list, It's danger!"  
  14.     fi    
  15. done  



0 0
原创粉丝点击