shell脚本运算

来源:互联网 发布:vue.js 显示和隐藏div 编辑:程序博客网 时间:2024/05/02 01:12

shell脚本中的数学运算和条件判断
运算符:
 +  加法
 -  减法
 *  乘法
 /  除法
 %  取余
 **  幂运算
 =  赋值
 +=      n+=m    n = n + m
 -=
 *=
 /=
 %=


数学运算三种方式:
方式1:
 echo `expr $n + $m`
 运算符和数据之间必须有空格
方式2:
 [$n+$m]
方式3:
 let data=$n+$m
 echo $data
 运算符和数据之间不能有空格

read 变量名
 read 变量名1 变量名2

。。。。。。。。。。。。。。。。。。。。。。。。。

echo "请输入一个四位整数"
read num
let data=$num%10
echo $num "的个位是" $data
let data=$num/10%10
echo $num "的十位是" $data
let data=$num/100%10
echo $num "的百位是" $data
let data=$num/1000%10
echo $num "的千位是" $data
let data=$num%10+$num/10%10+$num/100%10+$num/1000%10
echo $num "的各个位上数之和为:" $data

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

判断 test []
流程控制
 if
 then
 fi
 if
 then
 else
 fi

 if
 then
 else if
 then
 fi


 if test -z $str
 then
  echo  "str是空串"
 fi


test 的选项
 ! 非
 -a 逻辑与    and   并且 两个都为真 就为真
 -o 逻辑或    or    或者 两个中有一个为真就为真
 -n 判断字符串是否不是空串
 -z 判断字符串是否空串
 =  比较两个字符串是否相同
 != 比较两个字符串是否不同
 -eq 比较两个整数是否相等 equal
  ==
 -ge 比较第一个整数是否大于或等于第二个整数    greater or equal
  >=
 -gt 比较第一个整数是否大于第二个整数 greater than
  >
 -le less or equal
  <=
 -lt less than
  <
 -ne 比较两个整数是否不相等 no equal
  !=
 
 -f  是不是一个普通文件
 -d  是不是一个目录文件
 -w  文件是否拥有写权限
 -r  文件是否拥有读权限
 -x  文件是否拥有执行权限
 -e  文件是否存在


。。。。。。。。。。。。。。。。。。。。

echo "请输入一个文件名"
read file
if test -e $file
then
 echo "文件存在"
 if test -x $file
 then
  echo $file "拥有执行权限"
  ./$file
 else
  echo $file "没有执行权限"
  chmod +x $file
  ./$file
 fi
else
 echo "文件不存在"
fi


。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

echo "请输入一个整数"
read num
if test $num
then
 echo "输入的是字符串"
else 
n=0
if test $num -eq $n
then
 echo "您输入的是" $num
elif test $num -gt $n
then
 echo "您输入的是正数"
else
 echo "您输入的是负数"
fi
fi


。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

echo "请输入一个字符串"
read str1 str2
if [ $str1 = $str2 ]
then
 echo "str1等于str2"
else
 echo "str1和str2不一样"
fi

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

echo "请输入一个文件名"
read file_name
if test -e $file_name
then
 echo $file_name "文件存在"
 ls -l  $file_name
fi

0 0