shell脚本用到的代码片段

来源:互联网 发布:手机汽车设计软件 编辑:程序博客网 时间:2024/05/16 06:14
hello world程序  #!/bin/sh  str="hello world"  echo $str        #使用echo来打印  echo "shell, ${str} "数字  num=3       #数字  str2=${str}" is ok "${num}  #字符串连接  echo $str2数学计算  num1=4  i=$(($num*$num1))   #我更倾向于使用这个来进行数学计算  echo $i  j=$(expr $num + $num1)  echo $j  k=$(expr $num \* $num1)  echo $kif语句  if [ $num1 == 4 ];then     echo "num is 4"  fi  num2=2;  if [ $num2 == 4 ]; then    echo "num2 is 4 "  elif [ $num2 == 3 ]; then    echo "num2 is 3"   else    echo "not"  fi;与或非  # -a 表示 and  不推荐使用&&, 使用&& 需要进行转义  if [  $num2 == 2  -a  $num1 == 4    ]; then     echo "num2 is 2 and num1 is 4"  fi  # -o 表示or  不推荐使用||  if [ $num2 == 3 -o $num1 == 2 ];then     echo "num2 is 3 or num1 is 2"  else     echo "num2!=3 and num1!=2"  fi   if [ -n $num3 ]; then #判断num3有没有赋值    echo "nums is null"  else    echo "num3 is not null"   fi大于,小于,等于  # -lt  less than , 表示<  num=3  if [ $num -lt 3 ];then    echo "$num < 3"  else    echo "$num >=3 "  fi  # -le  less or equal , 表示<=  num=3  if [ $num -le 3 ];then    echo "$num <= 3"  else    echo "$num >3 "  fi  # -ge  great equal than, 表示>=  num=3  if [ $num -ge 3 ];then    echo "$num >= 3"  else    echo "$num <3 "  fi  # -gt  greater than, 表示>  num=3  if [ $num -gt 3 ];then    echo "$num > 3"  else    echo "$num <= 3 "  fi文件或目录,文件内容判断  if [ -f "/etc/hosts" ]; then    echo "/etc/hosts is a file"  fi  if [ -f "/etc" ];then     echo "/etc is a file"  #不成立,/etc/是一个目录  fi;  if [ ! -f "/etc" ];then   # ! -f 表示判断不是一个文件     echo "/etc is not a file"  #不成立,/etc/是一个目录  fi;  if [ -d "/etc" ];then     echo "/etc is a directory"    fi  if [ ! -d "/etc" ];then     echo "/etc is not a directory"  fi  #判断a.txt中是否有abc这个字符串  if grep  "abc" a.txt;then         echo "a.txt contain abc"  else     echo "a.txt not contain abc"  fi  #判断a.txt中最后200行,有没有abc这个字段  if tail -200 a.txt|grep "abc" ; then     echo "-200 a.txt contain abc"  else     echo "-200 a.txt not contain abc"  fifor循环  for var in 1,2,3; do    echo $var  done  #打印文件名  for file in `ls `; do     echo $file  donewhile循环  i=0  while [ $i != 10 ];do    echo $i    i=$(($i + 1))  done  # -lt  是< 的意思  i=0  while [ $i -lt 10 ];do     echo $i     i=$(($i+1))  donewhile读取输入,读取文件  while read line  do    if [ $line == "exit" ]; then      break;    fi    echo $line  done  #读取id.txt的内容,并组装url调用,把调用结果追加到result.log 中  cat id.txt |while read id  do     curl  "http://v.juhe.cn/weather/index?key="${id} >> result.log  done判断某个文件的最后修改时间与给定时间的大小关系判断  date1="2016-07-09 14:47:00"  date2=`stat top.log|tail -1|awk '{print $2}'`   #获取top.log的最后修改时间  t1=`date -d "${date1}" +%s`  t2=`date -d "${date2}" +%s`  echo $t1   #输出是unixstamp,精确到毫秒  echo $t2  if [ $t1 -gt $t2 ];then     echo "${date1} > ${date2} "  elif [ $t1 -eq $t2 ];then     echo "${date1} == ${date2}"  else     echo "${date1} < ${date2}"  fi