Linux shell脚本之 if条件判断 |
您所在的位置:网站首页 › shell等于怎么写 › Linux shell脚本之 if条件判断 |
shell基本语法
shell中将命令结果赋值给变量
var=`command`
var=$(command) # 推荐是用这种方式,支撑嵌套
shell 脚本中变量的数学计算
shell声明变量类型 declare -i x x=1+1 echo $x SHELL脚本获取自身所在路径和名字 #!/bin/bash BaseName=$(basename $BASH_SOURCE) # https://xvcat.com/post/1096 shell脚本实现:每10秒打印一次系统时间,连续打印10次 #/bin/bash i=1 while [ $i -le 10 ] do date sleep 10 let i++ done shell脚本实现每隔10s执行一次top命令,执行100次结束 n=0;while(($n 把输出转向就可以了 例子: $ ls > ls.txt #或者 ls-->ls.txt #把ls命令的运行结果保存到文件ls.txt中 说明: > 是把输出转向到指定的文件,如文件已存在的话也会重新写入,文件原内容不会保留 >> 是把输出附向到文件的后面,文件原内容会保留下来 shell除法显示小数 shell计算中使用除法,基本默认上都是整除。 比如: num1=2 num2=3 num3=`expr $num1 / $num2` 这个时候num3=0 ,是因为是因为expr不支持浮点除法 解决的方法: num3=`echo "sclae=2; $num1/$num2" | bc` 使用bc工具,sclae控制小数点后保留几位 还有一种方法 awk 'BEGIN{printf "%.2f\n",’$num1‘/’$num2‘}' 如果用百分比表示 awk 'BEGIN{printf "%.2f%\n",(’$num1‘/’$num2‘)*100}' 玩转Bash脚本:循环结构之while循环 参考:https://blog.csdn.net/guodongxiaren/article/details/43341769 IF条件判断1、基本语法: if [ command ]; then 符合该条件执行的语句 fi2、扩展语法: if [ command ];then 符合该条件执行的语句 elif [ command ];then 符合该条件执行的语句 else 符合该条件执行的语句 fi3、语法说明: 注意: 1、[ ]表示条件测试。注意这里的空格很重要。要注意在'['后面和']'前面都必须要有空格 2、在shell中,then和fi是分开的语句。如果要在同一行里面输入,则需要用分号将他们隔开。 3、注意if判断中对于变量的处理,需要加引号,以免一些不必要的错误。没有加双引号会在一些含空格等的字符串变量判断的时候产生错误。比如[ -n "$var" ]如果var为空会出错 4、判断是不支持浮点值的 5、如果只单独使用>或者 STRING2 ] 如果 “STRING1”字典排序在“STRING2”后面则返回为真。 数值判断 [ INT1 -eq INT2 ] INT1和INT2两数相等返回为真 ,= [ INT1 -ne INT2 ] INT1和INT2两数不等返回为真 , [ INT1 -gt INT2 ] INT1大于INT2返回为真 ,> [ INT1 -ge INT2 ] INT1大于等于INT2返回为真,>= [ INT1 -lt INT2 ] INT1小于INT2返回为真 ,< [ INT1 -le INT2 ] INT1小于等于INT2返回为真,b且a b )) && (( a < c )) [[ $a > $b ]] && [[ $a < $c ]] [ $a -gt $b -a $a -lt $c ]9:a>b或a b )) || (( a < c )) [[ $a > $b ]] || [[ $a < $c ]] [ $a -gt $b -o $a -lt $c ] 10:检测执行脚本的用户 if [ "$(whoami)" != 'root' ]; then echo "You have no permission to run $0 as non-root user." exit 1; fi 上面的语句也可以使用以下的精简语句 [ "$(whoami)" != 'root' ] && ( echo "You have no permission to run $0 as non-root user."; exit 1 ) 11:正则表达式 doiido="hero" if [[ "$doiido" == h* ]];then echo "hello,hero" fi ============其他例子============ 1、查看当前操作系统类型 #!/bin/sh SYSTEM=`uname -s` if [ $SYSTEM = "Linux" ] ; then echo "Linux" elif [ $SYSTEM = "FreeBSD" ] ; then echo "FreeBSD" elif [ $SYSTEM = "Solaris" ] ; then echo "Solaris" else echo "What?" fi 2、if利用read传参判断 #!/bin/bash read -p "please input a score:" score echo -e "your score [$score] is judging by sys now" if [ "$score" -ge "0" ]&&[ "$score" -lt "60" ];then echo "sorry,you are lost!" elif [ "$score" -ge "60" ]&&[ "$score" -lt "85" ];then echo "just soso!" elif [ "$score" -le "100" ]&&[ "$score" -ge "85" ];then echo "good job!" else echo "input score is wrong , the range is [0-100]!" fi 3、判断文件是否存在 #!/bin/sh today=`date -d yesterday +%y%m%d` file="apache_$today.tar.gz" cd /home/chenshuo/shell if [ -f "$file" ];then echo "OK" else echo "error $file" >error.log mail -s "fail backup from test" [email protected] |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |