#! /bin/sh
echo "please input x y";
read x y; #连续输入一组参数 以空格隔开
z=`expr $x+$y`;
echo "The sum is $z"
$? 是上一条命令的终止状态, 相当于C语言的main函数的返回值。
字符串比较 =、!=、-n、-z判断相等,不等,长度大于零,长度等于0
#! /bin/Bash
echo "please x y .if 0 is = then !="
read i y
[ "$i" = "$y" ]
echo $? #保存前一个命令的返回码
#! /bin/Bash
read i
[ -n "$i" ]
echo $? #保存前一个命令的返回码
数字比较 test语句来比较
-eq 相等 | -ge大于等于 | -le 小于等于| -ne 不等于 | -gt 大于 | -lt 小于
#! /bin/Bash
read x y
if test $x -eq $y
then
echo "$x=$y"
else
echo "$x!=$y"
fi
逻辑操作
!反:与一个逻辑值相反的逻辑值
-a 与(and) :两个逻辑值为“是”返回为“是”,反之为否
-o 或(or):两个逻辑值有一个为“是”则为是
#! /bin/Bash
str1="hehe"
str2=""
str3="hehe"
echo "is equals"
[ "$str1" -a "$str2" ]
echo $?
[ "$str1" -a "$str3" ]
echo $?
[ "$str1" -o "$str3" ]
echo $?
[ "$str1" -o "$str2" ]
echo $?
文件操作
-d 判断对象存在且为目录
-f 判断对象存在且为文件
-L 对象存在且为符合连接
-r 对象存在且可读
-s 对象存在且长度非零
-w 对象存在且可写
-x 对象存在且可执行
判断 /lw 为文件则 ls,为文件则读取内容
if [ -d /lw ]; then ls; elif [ -f /lw ]; then cat /lw; else echo "error"; fi
for 操作 ,in的列表中 空格表示换行
for i in a,b,c I,2 3,5; do echo $i; done
#for语句中的双括号不能省,最后的分号可有可无,表达式temp=`expr $temp + $j`的加号两边的空格不能省,否则会成为字符串的连接。
#! /bin/Bash
temp=0
for((i=0;i<100;i++))
do
temp=`expr $temp + $i`
done
echo "The result is $temp"
while 循环
#! /bin/Bash
temp=0
num=0
while(($num<=100))
do
temp=` expr $temp + $num `
num=` expr $num + 1`
done
echo "The result is $temp"
until 循环
重复do和done之间的操作直到表达式成立为止。
#! /bin/Bash
temp=0
num=0
until [ $num -gt 100 ]
do
temp=` expr $temp + $num `
num=` expr $num + 1`
done
echo " The result is $temp"
for+if 结合语法。
if 语法格式为:
if 比较式
then 操作
elif 比较式
then 操作
......
else 操作
fi 结束符
#! /bin/Bash
for((i=0;i<10;i++))
do
if(($i==1))
then
echo "This is 1"
elif(($i==2))
then
echo "This is 2"
elif(($i==3))
then
echo "This is 3"
elif test $i -eq 4
then
echo "This is 4"
else
echo "This is othen : $i"
fi
done
case 表达式 in
值1|值2)
操作;;
值3|值4)
操作;;
值5|值6)
操作;;
*)
操作;;
esac
Shell的函数
函数名( )
{
函数体
}
函数调用方式为
函数名 参数列表
函数定义完成后必须同时写出函数的调用
#! /bin/Bash
add()
{
a=$1
b=$2
z=` expr $a + $b `
echo "The sum is :$z"
}
add $1 $2
执行
[root@localhost bin]#./ test18 10 20
The sum is 30
在刚刚学习写shell 批处理时候,进行逻辑运算中,少不了需要进行基础的:四则运算,这里说说在linux shell 里面简单的实现方法。
1.简单方法
$ b=$((5*5+5-3/2))
$ echo $b
29
在linux shell中,我们可以使用 $(()) 将表达式放在括号中,即可达到运算的功能。
2.其它方法:
用:expr 实现运算
$ expr 5 - 4
1
注意:将需要运算的表达式写入在expr 后面即可,保证 参数与运算符号中间有空格隔开。
数组变量操作
方法一: 一次赋一个值
数组名[下标]=变量值
# array[0]=pear
# array[1]=apple
# array[2]=orange
# array[3]=peach
方法二: 一次赋多个值
# array=(tom jack alice)
# array=(`cat /etc/passwd`) 希望是将该文件中的每一个行作为一个元数赋值给数组array3
# array=(`ls /var/ftp/shell/for*`)
# array=(tom jack alice "bash shell")
# declare -a
declare -a array='([0]="pear" [1]="apple" [2]="orange" [3]="peach")'
declare -a array='([0]="tom" [1]="jack" [2]="alice")'
访问数组元数:
# echo ${array[0]} 访问数组中的第一个元数
# echo ${array[@]} 访问数组中所有元数 等同于 echo ${array1[*]}
# echo ${#array[@]} 统计数组元数的个数
# echo ${array[@]:1} 从数组下标1开始
# echo ${array[@]:1:2} 从数组下标1开始,访问两个元素