用镜头记录,用心灵体验 | 订阅本站 | 所有笔记 | 亲和力设计 | 流量

DB2 学习笔记

博客话题:DB2,Linux,Web,业余无线电,户外,摄影,截拳道,Thankpad,其他

软件开发

Shell 编程学习笔记

在当前shell中而不是子Shell中执行cmd.sh程序:

$ source cmd.sh 

或者

$ . cmd.sh

test 用于测试一个表达式的返回值:

if test "$1" = "abc" 
then
cmd
fi

可以用[]代替'test'关键字:

if [ "$1" = "abc" ]
then
cmd
fi

但[后和]前必须留有空格,等号两边也要留空格。
一些比较运算符:前面一列用于整形数据,后面一列用于字符串数据

-lt <
-gt >
-lq >=
-gq <=
-ne !=
-eq =

其他参数:

-n "str" 串是否不为空
-e "filename" 文件是否存在
-f "filename" 文件是否是普通文件
-d "filename" 是否是目录

shell后面的参数:

$# 参数的个数,不包括命令本身
$? 最后一个进程返回值
$0 命令本身
$1 第一个参数,依次类推:$2,$3...
$@ 所有的参数,形如:"$1" "$2" "$3" ...
$$ 包含当前进程ID
$! 最后一个后台进程的ID

可以用如下shell取出传入参数:

#!/bin/bash
if [ $# -lt 6 ]
then
echo usage: -a para1 
echo [-b para2] [-c para3]
exit 0
fi
for element in #@
do
if [ "$1" = "-a" ]
then
var1="$2"
elif [ "$1" = "-b" ]
then
var2="$2"
elif [ "$1" = "-c" ]
then
var3="$2"
fi
shift # 改变参数的引用,$2变成$1, $3变成$2 ...
done

注意:shift命令将会改变'$@'的值,循环结束后,'$@'值变为null。

有关awk的使用:

### m.tmp ###
table1
table2
...
#############

把m.tmp文件中的每一行前后插入字符串,并写回文件:

cat m.tmp | awk '{ print "delete from " $1 ";" }' > m.tmp

避免交互过程,一次性设定新密码:

echo "newpasswd" | passwd --stdin username

从命令行读入:

#!/bin/sh
while true
do
echo "are you sure to do this? [y/n]"
read str
if [ "$str" = "y" -o "$str" = "Y" ]
then
break
if [ "$str" = "n" -o "$str" = "N" ]
then
exit 0
else
continue
fi
done

read 后面可以不声明变量,则用户输入会写入默认变量$REPLY.

 

Alex's picture

my email address in picture

搜索|Search

评论|Recent Comments

按月归档|By Month

2009
07
2008
11
10
07
05
04
03
02
01
2007
12
10
07
06
05
04
03
02
01
2006
12
11
10
09
08
07
06
05
04
03
02
01
2005
11
10
09
08
07
04
03
2004
12
11
10
09
08
07
06
05
04
03
02
01
2003
12
10
09
08
06
2002
09
08
04
03
02
2001
12
09
07
06
05

我读|My Books

我的链接|My Links

我的朋友|My Friends

Creative Commons License
This blog is licensed under a Creative Commons License.
Movable Type 4 Logo