本系列针对Bash Shell,其他的比较流行的Shell还有Korn shell (ksh)和”Tenex C shell” (tcsh

)。
一 简单过程
1)可以使用任意一种文字编辑器,比如nedit、kedit、emacs、vi等来编写shell脚本。ubuntu中可以使用gedit,notpad++也不错啊。
2)文件必须以#!/bin/sh开始。符号#!用来告诉系统那个shell来执行该脚本的程序,系统中可以有多个shell,例如使用/bin/sh,/bin/bash。
3)编辑结束并保存后,如果要执行该脚本,必须先使其可执行,使用命令chmod +x filename。
4)此后在该脚本所在目录下,输入 ./filename 即可执行该脚本。
5)最简单的调试方法当然是使用echo命令。你可以在任何怀疑出错的地方用echo打印变量值。
6)可以用sh -x strangescript来调试。
7)可以使用sh -n your_script来检查语法,不执行。
8)以# 开始的行表示注释,直到该行的结束。

二 命令
可以使用所有的Unux的命令。

三 变量
Shell编程中,使用变量无需事先声明,同时变量名的命名须遵循如下规则:1. 首个字符必须为字母(a-z,A-Z)2. 中间不能有空格,可以使用下划线(_)3. 不能使用标点符号 4. 不能使用bash里的关键字(可用help命令查看保留关键字)。
要给变量赋值时,可以这么写:变量名=值, 等号两边均不能有空格存在。为了避免混淆,可以使用{}给变量,如${num}。

四 管道/重定向
*  管道 (|) :将一个命令的输出作为另外一个命令的输入 :grep “hello” file.txt | wc -l 。 上述命令会在file.txt中搜索包含有”hello”的行并计算行数,这里grep命令的输出成了wc命令的
输入。
* 重定向:将命令的结果输出到文件,而不是标准输出(屏幕) > 写入文件并复盖旧文件,>> 加到文件的尾部,保留旧文件内容。
* 反短斜线:反短斜线可以将一个命令的输出作为其它命令的命令行参数。find . -mtime -1 -type f -print。上述命令可以查找过去24小时(-mtime –2则表示过去48小时)内修改过的文件。如果您想将所有查找到的文件打一个包,则可以使用以下脚本:
#!/bin/sh
# The ticks are backticks (`) not normal quotes  (\’):
tar -zcvf lastmod.tar.gz `find . -mtime -1 -type f -print`
* 单引号‘’:功能则最强。当你把字符串用单引号括起来时,外壳将忽视所有单引号中的特殊字符。
* 双引号“”:双引号的功能最弱。当你把字符串用双引号括起来时,外壳将忽略字符串中的空格,但其他的字符都将继续起作用。双引号在将多于一个单词的字符串赋给一个变量时尤其有用。
* 反斜杠\:反斜杠的功能和单引号一样,只是反斜杠每次只能使一个字符发生转义,而不是使整个字符串发生转义。

五 特殊字符
• 有些变量在启动外壳时就已经存在于系统中,你可以使用这些系统变量,并且可以赋予
新值:
$HOME 用户自己的目录。
$ PATH 执行命令时所搜寻的目录。
$TZ 时区。
$MAILCHECK 每隔多少秒检查是否有新的邮件。
$ P S 1 在外壳命令行的提示符。
$ P S 2 当命令尚未打完时,外壳要求再输入时的提示符。
$ M A N PATHman 指令的搜寻路径。
• 有些变量在执行外壳程序时系统就设置好了,并且你不能加以修改:
$ # 存储外壳程序中命令行参数的个数。
$ ? 存储上一个执行命令的返回值。
$ 0 存储外壳程序的程序名。
$ * 存储外壳程序的所有参数。
$ @ 存储所有命令行输入的参数,分别表示为(“$ 1” “$ 2” . . . )。shift 命令用来将存储在位置参数中的当前值左移一个位置。
$ $ 存储外壳程序的P I D。
$ ! 存储上一个后台执行命令的P I D。

六 关键字
1)if
if [ expression ]
then
commands
elif [ expression2 ]
then
commands
else
commands
fi
2)条件,条件之间可以使用&& 和||

-b file            若文件存在且是一个块特殊文件,则为真
-c file           
若文件存在且是一个字符特殊文件,则为真
-d file           
若文件存在且是一个目录,则为真
-e file           
若文件存在,则为真
-f file           
若文件存在且是一个规则文件,则为真
-g file           
若文件存在且设置了SGID位的值,则为真
-h file           
若文件存在且为一个符合链接,则为真
-k file           
若文件存在且设置了“sticky”位的值
-p file           
若文件存在且为一已命名管道,则为真
-r file           
若文件存在且可读,则为真
-s file           
若文件存在且其大小大于零,则为真
-u file           
若文件存在且设置了SUID位,则为真
-w file           
若文件存在且可写,则为真
-x file           
若文件存在且可执行,则为真
-o file           
若文件存在且被有效用户ID所拥有,则为真

-z string          string长度为0,则为真
-n string         
string长度不为0,则为真
string1 = string2 
若两个字符串相等,则为真
string1 != string2
若两个字符串不相等,则为真

int1 -eq int2      int1等于int2,则为真
int1 -ne int2     
int1不等于int2,则为真
int1 -lt int2     
int1小于int2,则为真
int1 -le int2     
int1小于等于int2,则为真
int1 -gt int2     
int1大于int2,则为真
int1 -ge int2     
int1大于等于int2,则为真

!expr              expr为假则复合表达式为真。expr可以是任何有效的测试表达式
expr1 -a expr2    
expr1expr2都为真则整式为真
expr1 -o expr2    
expr1expr2有一个为真则整式为真

3)case
case string1 in
str1 )
commands ; ;
str2 )
commands ; ;
* )
commands ; ;
esac
4)for
for var1 in list
do
commands
done
5)while
while expression
do
statements
done
6)until
until expression
do
commands
done
7)select
select menuitem [in list_of_items]
do
commands
done

 

七 子函数
fname () {
shellcommands
}
调用fname [parm1 parm2 parm3 …]

 

实例:

http://intuitive.com/wicked/scripts/053-verifycron.txt

https://github.com/djura-san/100-shell-script-examples/blob/master/053-verifycron.sh

  1. #!/bin/sh
  2.  
  3. # verifycron - script checks a crontab file to ensure that it\'s
  4. # formatted properly. Expects standard cron notation of
  5. # min hr dom mon dow CMD
  6. # where min is 0-59, hr 0-23, dom is 1-31, mon is 1-12 (or names)
  7. # and dow is 0-7 (or names). Fields can have ranges (a-e), lists
  8. # separated by commas (a,c,z), or an asterisk. Note that the step
  9. # value notation of Vixie cron is not supported (e.g., 2-6/2).
  10.  
  11.  
  12. validNum()
  13. {
  14. # return 0 if valid, 1 if not. Specify number and maxvalue as args
  15. num=$1 max=$2
  16.  
  17. if [ "$num" = "X" ] ; then
  18. return 0
  19. elif [ ! -z $(echo $num | sed \'s/[[:digit:]]//g\') ] ; then
  20. return 1
  21. elif [ $num -lt 0 -o $num -gt $max ] ; then
  22. return 1
  23. else
  24. return 0
  25. fi
  26. }
  27.  
  28. validDay()
  29. {
  30. # return 0 if a valid dayname, 1 otherwise
  31.  
  32. case $(echo $1 | tr \'[:upper:]\' \'[:lower:]\') in
  33. sun*|mon*|tue*|wed*|thu*|fri*|sat*) return 0 ;;
  34. X) return 0 ;; # special case - it\'s an "*"
  35. *) return 1
  36. esac
  37. }
  38.  
  39. validMon()
  40. {
  41. # return 0 if a valid month name, 1 otherwise
  42.  
  43. case $(echo $1 | tr \'[:upper:]\' \'[:lower:]\') in
  44. jan*|feb*|mar*|apr*|may|jun*|jul*|aug*) return 0 ;;
  45. sep*|oct*|nov*|dec*) return 0 ;;
  46. X) return 0 ;; # special case, it\'s an "*"
  47. *) return 1 ;;
  48. esac
  49. }
  50.  
  51. fixvars()
  52. {
  53. # translate all \'*\' into \'X\' to bypass shell expansion hassles
  54. # save original as "sourceline" for error messages
  55.  
  56. sourceline="$min $hour $dom $mon $dow $command"
  57. min=$(echo "$min" | tr \'*\' \'X\')
  58. hour=$(echo "$hour" | tr \'*\' \'X\')
  59. dom=$(echo "$dom" | tr \'*\' \'X\')
  60. mon=$(echo "$mon" | tr \'*\' \'X\')
  61. dow=$(echo "$dow" | tr \'*\' \'X\')
  62. }
  63.  
  64. if [ $# -ne 1 ] || [ ! -r $1 ] ; then
  65. echo "Usage: $0 usercrontabfile" >&2; exit 1
  66. fi
  67.  
  68. lines=0 entries=0 totalerrors=0
  69.  
  70. while read min hour dom mon dow command
  71. do
  72. lines="$(( $lines + 1 ))"
  73. errors=0
  74. if [ -z "$min" -o "${min%${min#?}}" = "#" ] ; then
  75. continue # nothing to check
  76. elif [ ! -z $(echo ${min%${min#?}} | sed \'s/[[:digit:]]//\') ] ; then
  77. continue # first char not digit: skip!
  78. fi
  79.  
  80. entries="$(($entries + 1))"
  81.  
  82. fixvars
  83.  
  84. #### Broken into fields, all \'*\' replaced with \'X\'
  85. # minute check
  86.  
  87. for minslice in $(echo "$min" | sed \'s/[,-]/ /g\') ; do
  88. if ! validNum $minslice 60 ; then
  89. echo "Line ${lines}: Invalid minute value \"$minslice\""
  90. errors=1
  91. fi
  92. done
  93.  
  94. # hour check
  95. for hrslice in $(echo "$hour" | sed \'s/[,-]/ /g\') ; do
  96. if ! validNum $hrslice 24 ; then
  97. echo "Line ${lines}: Invalid hour value \"$hrslice\""
  98. errors=1
  99. fi
  100. done
  101.  
  102. # day of month check
  103.  
  104. for domslice in $(echo $dom | sed \'s/[,-]/ /g\') ; do
  105. if ! validNum $domslice 31 ; then
  106. echo "Line ${lines}: Invalid day of month value \"$domslice\""
  107. errors=1
  108. fi
  109. done
  110.  
  111. # month check
  112.  
  113. for monslice in $(echo "$mon" | sed \'s/[,-]/ /g\') ; do
  114. if ! validNum $monslice 12 ; then
  115. if ! validMon "$monslice" ; then
  116. echo "Line ${lines}: Invalid month value \"$monslice\""
  117. errors=1
  118. fi
  119. fi
  120. done
  121.  
  122. # day of week check
  123.  
  124. for dowslice in $(echo "$dow" | sed \'s/[,-]/ /g\') ; do
  125. if ! validNum $dowslice 7 ; then
  126. if ! validDay $dowslice ; then
  127. echo "Line ${lines}: Invalid day of week value \"$dowslice\""
  128. errors=1
  129. fi
  130. fi
  131. done
  132.  
  133. if [ $errors -gt 0 ] ; then
  134. echo ">>>> ${lines}: $sourceline"
  135. echo ""
  136. totalerrors="$(( $totalerrors + 1 ))"
  137. fi
  138. done < $1
  139.  
  140. echo "Done. Found $totalerrors errors in $entries crontab entries."
  141.  
  142. exit 0

  

完!

 

版权声明:本文为itech原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/itech/archive/2011/12/31/1431219.html