Linux学习随笔-shell简单编写

发表于:2016-5-31 09:26

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:flex-    来源:51Testing软件测试网原创

  脚本最好都放在/usr/local/sbin中
  脚本的执行 sh -x 脚本.sh -x可以查看执行过程
  1、在脚本中使用变量 使用变量的时候,需要使用$符号:
  #!/bin/bash
  ##把命令赋值为变量,需要使用反引号
  d=`date +"%H:%M:%S"`
  echo "The script begin at $d"
  echo "Now we'll sleep 2 seconds"
  sleep 2
  d1=`date +"%H:%M:%S"`
  echo "The script end at $d"
  2、在脚本中使用数学运算要用[]括起来如下
  #! /bin/bash
  a=1
  b=2
  ##数学运算用[]括起来
  sum=$[$a+$b]
  echo "$a + $b = $sum"
  3、在脚本中和控制台交互 使用read命令
  #! /bin/bash
  read -p "Please input a number: " x
  read -p "Please input a number: " y
  sum=$[$x+$y]
  echo "The sum of the tow numbers is : $sum"
  4、shell中的预设变量
  #! /bin/bash
  echo "$1 $2 $3 $0"
  1 2 就是脚本中的预设变量 一个脚本中的预设变量是没有限制的,0表示脚本文件本书
  # sh option.sh 1 2 3
  执行此命令输出内容如下所示:
  1 2 3 option.sh
  5、shell中的逻辑判断
  不带else的if 注意if后面的判断语句要用(())否则会报错
  #! /bin/bash
  read -p "Please input your score: " a
  if ((a<60)); then
  echo "You didn't pass the exam."
  fi
  5.1、带else 实例代码如下
  #! /bin/bash
  read -p "Please input your score: " a
  if ((a<60)); then
  echo "You didn't pass the exam."
  else
  echo "Good! You passed the exam."
  fi
  5.2、带有else if(这是c中的说法)在shell中表示为elif
  #! /bin/bash
  read -p "Please input your score: " a
  if ((a<60)); then
  echo "You didn't pass the exam."
  elif ((a>=60)) && ((a<85)); then
  echo "Good! You passed the exam."
  else
  echo "Very good! Your score is very heigh"
  fi
  5.3、case 逻辑判断
  #! /bin/bash
  read -p "Input a number: " n
  a=$[$n%2]
  case $a in
  1)
  echo "The number is odd."
  ;;
  0)
  echo "The number is even."
  ;;
  *)
  echo "It's not a number"
  ;;
  esac
  * 表示其他值
  6、for循环
  实例代码如下:
  #! /bin/bash
  for file in `ls`;do
  echo $file
  done
  7、while 循环
  #! /bin/bash
  a=5
  while [ $a -ge 1 ]; do
  echo $a
  a=$[$a-1]
  done
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号