终于学到
shell编程了,之前做了好多准备,呵呵。现在把我学到的总结如下:
先写段完整代码:
#!/bin/bash
#program:
this program is an example of shell.
#History:
2009/10/12 navy first release
PATH=
(可以由echo $PATH来获得) export PATH
echo "hello to the world!"
比如保存在sh01.sh中
执行命令:sh sh01.sh
屏幕上显示:hello to the world!
一、执行shell脚本命令1、将shell.sh加上可读执行rx权限,然后用./shell.sh来执行即可
2、用sh shell.sh的方式来直接执行
二、判断条件判断条件,在脚本中用的比较多,[]或
test都起到判断的目的,比如判断一个文件sh01.sh是否存在,可以有这样两种方法:test -e sh01.sh、
[ -e "sh01.sh" ]
1、某个文件名的”类型“检测:如: test -e filename
-e 该文件名是否存在
-f 该文件名是否为文件
-d 该文件名是否为目录
2、文件权限的检验:
-r:可读
-w:可写
-x:可执行
3、比较两个文件,比如:test file1 -nt file2
-nt: newer than 判断file1是否比file2新
-ot:older than 判断file1是否比file2旧
4、两个整数之间的判断,如:test n1 -eq n2
-eq:两数值相等。equal
-ne:not equal,不相等
-gt:greater than,大于
-lt:less than 小于
-ge:greater than or equal 大于等于
-le:less than or equal 小于等于
5、字符串判断
test -z string 判断字符串是否为0
test -n string 判断字符串是否非为0
test string1=string2 判断两个字符串是否相等
test string1!=string2 判断两个字符串是否不等
三、条件语句 if...thenif [ 条件表达式一 ]; then
当成立时,执行的命令
elif [ 条件表达式二 ]; then
当成立时,执行的命令
else
当条件1和2全不成立时,执行的命令
fi
eg:
#!/bin/bash
#program:
this program is an example of shell.
#History:
2009/10/12 navy first release
PATH=
(可以由echo $PATH来获得) export PATH
read -p "please input(y/n):" yn
if [ "$yn" == "y" ]; then
echo "ok,continue"
elif [ "$yn" == "n" ]; then
echo "oh,interrupt"
else
echo "i don't know what is your choice"
fi
四、case...esac判断格式:
case $变量名称 in
”第一个变量内容“)
程序段
;;
"第二个变量内容"
程序段
;;
*)
不包含第一个和第二个变量内容的
其他程序执行段
exit 1
;;
esac
eg:
#!/bin/bash
#program:
this program is an example of shell.
#History:
2009/10/12 navy first release
PATH=
(可以由echo $PATH来获得) export PATH
read -p "please input(y/n):" yn
case $yn in
"y")
echo "ok,continue"
;;
"n")
echo "oh,interrupt"
*)
echo "i don't know what is your choice"
;;
esac
五、循环:while do done、until do doneeg:
#!/bin/bash
#program:
this program is an example of shell.
#History:
2009/10/12 navy first release
PATH=
(可以由echo $PATH来获得) export PATH
i=0;
s=0
while[ "$i" -le "100"]
do
$s=$(($s+$i))
$i=$(($i+1))
done
echo $s
六、循环:for do done1、格式:
for(( 初始值; 限制值; 执行步长 ))
do
程序段
done
eg:
#!/bin/bash
#program:
this program is an example of shell.
#History:
2009/10/12 navy first release
PATH=
(可以由echo $PATH来获得) export PATH
s=0
for((i=0;i<=100;i++))
do
$s=$(($s+$i))
done
echo $s
2、非数字方面的循环运算
格式:
for var in con1,con2,con3...
do
程序段
done
说明,在第一次循环时,$var的内容为con1
在第二次循环时,$var的内容为con2
.....
eg:
#!/bin/bash
#program:
this program is an example of shell.
#History:
2009/10/12 navy first release
PATH=
(可以由echo $PATH来获得) export PATH
$file=`cat /etc/passwd | cut -d ":" -f 1`
i=1
for usr in $file
do
echo "the $i account is:"$usr""
i=$(($i+1))
done
说明:上面程序是取出账号名称,并打印出来。