一个bash script的简单例子(if case的使用)
授权方式:署名,非商业用途,保持一致,转载时请务必以超链接(http://www.fwolf.com/blog/post/171)的形式标明文章原始出处和作者信息及本声明。在局域网环境中工作,经常要访问别人的电脑,而他们大多还在使用windows,所以要反复的mount、umount共享目录,烦死了,并且不umount还不行,别人一关机,这边再操作就要停顿半天没反应。所以编写了一个小小的shell script,简化这些工作。代码、注释和说明都在一起了,应该不用再多解释了吧。
#! /bin/bash
# 如果不输入参数,则提示命令的用法
# 注意判断条件的这个表达式是用英文方括号[]包含的,
# 并且[后面和]前面必须各有一个空格,没有的话会报错
# 另外then必须另起一行,要不也报错
# 输出的字符串中包含|,所以必须引起来,不然就成了管道操作符了
# 如果实在不想用引号,可以在|前面加上\\就可以了
if [ 0 = $# ]
then
echo "Usage: mmount destination [d|del|delete]"
exit
fi
# 看看当前用户是否root用户,不是的话就要使用sudo
if [ 0 = $UID ]
then
SUDO=""
else
SUDO="sudo "
fi
# 根据第一个参数判断要处理的是那个共享目录
# 为了方面调用,共享目录名称采用了“机器名-共享目录名”的简单方式
# 在这里识别出来之后再指定其详细的参数
case $1 in
xjl-e) DEST=//xjl/e
MOUNTPOINT=/media/share/xjl-e
USERPWD=xjl%
;;
cmp-c) DEST=//cmp/c$
MOUNTPOINT=/media/share/cmp-c
USERPWD=cmp\\\\Admin%8008101818
;;
*) echo "Mount or umount: xjl-e/f/g/h, lh3000a-s, cmp-c, wf ?"
exit
;;
esac
# 根据第二个传入参数判断是否是需要umount的调用
# 多个判断条件用||表示OR关系,用&&表示AND关系
# OR和AND嵌套时,可以使用()来调整运算顺序
# ()后前不用加空格了,都快被[]的后前空格整疯了
if ([ "d"=$2 ] || [ "del"=$2 ] || [ "delete"=$2 ]) && [ ! -z $2 ]
then
$SUDO umount $MOUNTPOINT
rm -r $MOUNTPOINT
else
mkdir $MOUNTPOINT
$SUDO mount $DEST $MOUNTPOINT -o dmask=777,fmask=777,iocharset=utf8,codepage=cp936,username=$USERPWD
fi
PS: vi中用:TOhtml命令生成的html颜色代码怎么就和看起来差别那么大呢,选了半天也不知道用什么颜色的背景最合适。darkolivegreen ? midnightblue? yellowgreen ?
另外推荐一个比较不错的Bash教程网站——Advanced Bash-Scripting Guide,比gnu的bash文档写得详细多了,并且都带有范例。
Close this Window Bookmark and Share This Page
Copy HTML:
If you like this then please subscribe to the RSS Feed.
![[Bloglines]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/bloglines.png)
![[co.mments]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/comments.png)
![[del.icio.us]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/delicious.png)
![[Digg]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/digg.png)
![[diigo]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/diigo.png)
![[Facebook]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/facebook.png)
![[Furl]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/furl.png)
![[Google]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/google.png)
![[MySpace]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/myspace.png)
![[Reddit]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/reddit.png)
![[Rojo]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/rojo.png)
![[Slashdot]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/slashdot.png)
![[StumbleUpon]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/stumbleupon.png)
![[Technorati]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/technorati.png)
![[Windows Live]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/windowslive.png)
![[Yahoo!]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/yahoo.png)
![[Email]](http://www.fwolf.com/blog/wp-content/plugins/bookmarkify/email.png)