Shell脚本编程30分钟入门
来源:互联网 发布:全国淘宝店有多少家 编辑:程序博客网 时间:2024/05/29 04:44
在sh/bash里可不能这么写,如果else分支没有语句执行,就不要写这个else。
还要注意,sh里的if [ $foo -eq 0 ],这个方括号跟Java/PHP里if后面的圆括号大不相同,它是一个可执行程序(和cd, ls, grep一样),想不到吧?在CentOS上,它在/usr/bin目录下:
ll /usr/bin/[-rwxr-xr-x. 1 root root 33408 6月 22 2012 /usr/bin/[
正因为方括号在这里是一个可执行程序,方括号后面必须加空格,不能写成if [$foo -eq 0]
if else
if
if conditionthen command1 command2 ... commandN fi
写成一行(适用于终端命令提示符):
if `ps -ef | grep ssh`; then echo hello; fi
末尾的fi就是if倒过来拼写,后面还会遇到类似的
if else
if conditionthen command1 command2 ... commandNelse commandfi
if else-if else
if condition1then command1elif condition2 command2else commandNfi
for while
for
在开篇的示例里演示过了:
for var in item1 item2 ... itemNdo command1 command2 ... commandNdone
写成一行:
for var in item1 item2 ... itemN; do command1; command2… done;
C风格的for
for (( EXP1; EXP2; EXP3 ))do command1 command2 command3done
while
while conditiondo commanddone
无限循环
while :do commanddone
或者
while truedo commanddone
或者
for (( ; ; ))
until
until conditiondo commanddone
case
case "${opt}" in "Install-Puppet-Server" ) install_master $1 exit ;; "Install-Puppet-Client" ) install_client $1 exit ;; "Config-Puppet-Server" ) config_puppet_master exit ;; "Config-Puppet-Client" ) config_puppet_client exit ;; "Exit" ) exit ;; * ) echo "Bad option, please choose again"esac
case的语法和C family语言差别很大,它需要一个esac(就是case反过来)作为结束标记,每个case分支用右圆括号,用两个分号表示break
函数
定义
调用
文件包含
可以使用source和.关键字,如:
source ./function.sh. ./function.sh
在bash里,source和.是等效的,他们都是读入function.sh的内容并执行其内容(类似PHP里的include),为了更好的可移植性,推荐使用第二种写法。
包含一个文件和执行一个文件一样,也要写这个文件的路径,不能光写文件名,比如上述例子中:
. ./function.sh
不可以写作:
. function.sh
如果function.sh是用户传入的参数,如何获得它的绝对路径呢?方法是:
real_path=`readlink -f $1`#$1是用户输入的参数,如function.sh. $real_path
用户输入
执行脚本时传入
脚本运行中输入
select菜单
stdin和stdout
常用的命令
sh脚本结合系统命令便有了强大的威力,在字符处理领域,有grep、awk、sed三剑客,grep负责找出特定的行,awk能将行拆分成多个字段,sed则可以实现更新插入删除等写操作。
ps
0 0
- Shell脚本编程30分钟入门
- Shell脚本编程30分钟入门
- Shell脚本编程30分钟入门
- Shell脚本编程30分钟入门
- Shell脚本编程30分钟入门
- Shell脚本编程30分钟入门
- Shell脚本编程30分钟入门
- Shell脚本编程30分钟入门
- Shell脚本编程30分钟入门
- shell脚本编程入门
- 30分钟shell入门
- Linux Shell编程--入门脚本
- 《Linux shell脚本编程入门》
- linux Shell脚本编程入门
- 简单入门shell脚本编程
- Shell 脚本编程入门基础
- Bourne shell编程入门及脚本测试
- Bourne shell编程入门及脚本测试
- 收藏
- poj 1062 昂贵的聘礼 【最短路径-Dijkstra】
- eclipse中如何向开源中国(码云)上传代码
- 递归与伪递归区别,Python 实现递归与尾递归
- 那些年,我们一起写过的“单例模式”
- Shell脚本编程30分钟入门
- Fiddler教程:fiddler抓包时,出现的 tunnel to
- WebCollector爬虫学习记录(一)爬取国际石油网知识板块
- 简析数据库范式
- Ubuntu16.04 搭建VPN服务
- noi-7599-石头剪子布
- 《机导》学习感悟(一)
- 面向对象——概念(成员变量、静态变量、成员方法、静态方法、垃圾回收机制、重载、包)
- maven相关