本系列针对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     若expr1和expr2都为真则整式为真
expr1 -o expr2     若expr1和expr2有一个为真则整式为真
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

#!/bin/sh# verifycron - script checks a crontab file to ensure that it's
#    formatted properly.  Expects standard cron notation of
#       min hr dom mon dow CMD
#    where min is 0-59, hr 0-23, dom is 1-31, mon is 1-12 (or names)
#    and dow is 0-7 (or names).  Fields can have ranges (a-e), lists
#    separated by commas (a,c,z), or an asterisk. Note that the step
#    value notation of Vixie cron is not supported (e.g., 2-6/2).validNum()
{# return 0 if valid, 1 if not. Specify number and maxvalue as argsnum=$1   max=$2if [ "$num" = "X" ] ; thenreturn 0elif [ ! -z $(echo $num | sed 's/[[:digit:]]//g') ] ; thenreturn 1elif [ $num -lt 0 -o $num -gt $max ] ; thenreturn 1elsereturn 0fi
}validDay()
{# return 0 if a valid dayname, 1 otherwisecase $(echo $1 | tr '[:upper:]' '[:lower:]') insun*|mon*|tue*|wed*|thu*|fri*|sat*) return 0 ;;X) return 0    ;; # special case - it's an "*"*) return 1esac
}validMon()
{# return 0 if a valid month name, 1 otherwisecase $(echo $1 | tr '[:upper:]' '[:lower:]') in jan*|feb*|mar*|apr*|may|jun*|jul*|aug*) return 0      ;;sep*|oct*|nov*|dec*)           return 0       ;;X) return 0 ;; # special case, it's an "*"*) return 1  ;;esac
}fixvars()
{# translate all '*' into 'X' to bypass shell expansion hassles# save original as "sourceline" for error messagessourceline="$min $hour $dom $mon $dow $command"min=$(echo "$min" | tr '*' 'X')hour=$(echo "$hour" | tr '*' 'X')dom=$(echo "$dom" | tr '*' 'X')mon=$(echo "$mon" | tr '*' 'X')dow=$(echo "$dow" | tr '*' 'X')
}if [ $# -ne 1 ] || [ ! -r $1 ] ; thenecho "Usage: $0 usercrontabfile" >&2; exit 1
filines=0  entries=0  totalerrors=0while read min hour dom mon dow command
dolines="$(( $lines + 1 ))" errors=0if [ -z "$min" -o "${min%${min#?}}" = "#" ] ; thencontinue  # nothing to checkelif [ ! -z $(echo ${min%${min#?}} | sed 's/[[:digit:]]//') ] ;  thencontinue   # first char not digit: skip!fientries="$(($entries + 1))"fixvars#### Broken into fields, all '*' replaced with 'X' # minute checkfor minslice in $(echo "$min" | sed 's/[,-]/ /g') ; doif ! validNum $minslice 60 ; thenecho "Line ${lines}: Invalid minute value \"$minslice\""errors=1fidone# hour checkfor hrslice in $(echo "$hour" | sed 's/[,-]/ /g') ; doif ! validNum $hrslice 24 ; thenecho "Line ${lines}: Invalid hour value \"$hrslice\"" errors=1fidone# day of month checkfor domslice in $(echo $dom | sed 's/[,-]/ /g') ; doif ! validNum $domslice 31 ; thenecho "Line ${lines}: Invalid day of month value \"$domslice\""errors=1fidone# month checkfor monslice in $(echo "$mon" | sed 's/[,-]/ /g') ; doif ! validNum $monslice 12 ; thenif ! validMon "$monslice" ; thenecho "Line ${lines}: Invalid month value \"$monslice\""errors=1fifidone# day of week checkfor dowslice in $(echo "$dow" | sed 's/[,-]/ /g') ; doif ! validNum $dowslice 7 ; thenif ! validDay $dowslice ; thenecho "Line ${lines}: Invalid day of week value \"$dowslice\""errors=1fifidoneif [ $errors -gt 0 ] ; thenecho ">>>> ${lines}: $sourceline"echo ""totalerrors="$(( $totalerrors + 1 ))"fi
done < $1echo "Done. Found $totalerrors errors in $entries crontab entries."exit 0

  

完!

Linux sh/bash[精华]相关推荐

  1. linux sh/bash 编程常用

    本系列针对Bash Shell,其他的比较流行的Shell还有Korn shell (ksh)和"Tenex C shell" (tcsh ). 一 简单过程 1)可以使用任意一种 ...

  2. Linux下sh/bash/source/.命令的区别(转)

    一..sh文件介绍 .sh为Linux的脚本文件,我们可以通过.sh执行一些命令,可以理解为windows的.bat批处理文件. 二.点命令(.) .命令和source是同一个命令,可以理解为sour ...

  3. Linux~Sh脚本一点自己的总结

    从.netCore开源项目来看,eShopOnContainers来说,它的部署是跨平台的,可以部署在linux,docker上,在linux上运行它也可以写一些集成的小脚本,这是微信工程师为我们提供 ...

  4. 【Linux】一步一步学Linux——sh命令(225)

    00. 目录 文章目录 00. 目录 01. 命令概述 02. 命令格式 03. 常用选项 04. 参考示例 05. 附录 01. 命令概述 sh命令是shell命令语言解释器,执行命令从标准输入读取 ...

  5. linux下Bash编程until语句及格式化硬盘分区等编写脚本(十)

    linux下Bash编程until语句及格式化硬盘分区等编写脚本(十) 1.循环语句结构总结 1.1.while语句当条件满足时,进入循环语句 while 条件; do 语句 done 1.2.unt ...

  6. Linux 技巧: Bash 参数和参数扩展 (Shell)

    现在,很多 Linux® 和 UNIX® 系统上都有 bash shell,它是 Linux 上常见的默认 shell.通过本文,您将了解到如何在 bash 脚本中处理参数和选项,以及如何使用 she ...

  7. sh/bash/csh/Tcsh/ksh/pdksh等shell本质区别

    sh/bash/csh/Tcsh/ksh/pdksh等shell本质区别 1. Shell脚本的书写 在写Shell脚本时,往往第一行要注明用什么解释器来解释这个脚本. 如#!/bin/bash即用/ ...

  8. linux 中输入bash,Linux上Bash Shell编程

    Linux下Bash Shell编程 Bash Shell Programming in Linux Linux下Bash Shell编程 Bash what? 进阶的内容是什么? Okay, I g ...

  9. 基于Linux的bash/shell编程基础

    目录 第一章 shell入门 1.什么是shell 2.shell入门 3,变量的定义和使用 4.接收用户输入(重点) 5.条件判断语句 6.运算符 6.1.算数运算符 6.2.关系运算符 6.3.逻 ...

最新文章

  1. 36 岁开发者应聘被拒,这 3 位 50 岁程序员的生存秘籍送给你!
  2. RDP8.0来了,Windows 7可以升级RDP了
  3. C++练习 | C++从入门到放弃(基础+进阶C++ github)
  4. Ubuntu 14.04 LTS 下升级 gcc 到 gcc-4.9、gcc-5 版本
  5. Codeforces Round #694 Div. 2
  6. 一文搞懂JVM架构和运行时数据区,全网最新
  7. Vue中token刷新及token过期的实现
  8. centos7 rpm 安装 rabbitMQ 最新版
  9. python集合常用方法_Python 集合常用方法总结
  10. python多线程_thread使用锁
  11. 基于隐马尔可夫模型的有监督词性标注
  12. 伪数据科学家 VS 真数据科学家
  13. 程序猿学习中华古诗词路径
  14. 哈夫曼树实现:统计文本信息,构造哈夫曼树,并对其进行编码与解码
  15. oracle的dmp文件导入mysql_Oracle 数据库导入导出 dmp文件
  16. android MediaPlayer SurfaceView 网络视频播放器
  17. client wants service A, but it has B. Dropping connection.
  18. android x86 uc,UC浏览器X86版下载|UC浏览器X86版老版 V10.8.5 安卓版 下载_当下软件园_软件下载...
  19. python爬虫爬取百度文档
  20. H264视频高压心得——兼容华为U8800+(硬解720P)

热门文章

  1. 斐波那契数列-爬楼梯算法
  2. ES2021 更新的内容!
  3. java学习 类变量 类方法_这篇文章主要介绍了JAVA类变量及类方法代码实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下类变量(...
  4. fastdfs暗转 linux_Linux下安装fastDFS
  5. impala java api 操作_Impala实践之六:使用Rest Api
  6. Android刷新当前页面
  7. linux终端什么字体舒服,推荐一款 Linux 上比较漂亮的字体
  8. jquery bind button 点击事件
  9. html2canvas截图只截取当前可视区域的问题
  10. kafka内部消费偏移