Programming in Shell -- I

本文介绍了Shell脚本的基础知识,包括数值运算、条件判断、文件属性测试等实用技巧,并通过具体示例展示了如何使用if语句进行逻辑控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 数值运算

  var=$((expression))
   total=$(($firstnu*secnu))
   echo $total;
2. test 命令可用于判断某文件是否存在或其属性(如是否是文件或目录)
   fredchen@fredchen:~$ test -e dd || echo "this file does not exsist"
   this file does not exsist
   fredchen@fredchen:/dev$ test -b ttyze                         
   fredchen@fredchen:/dev$ test -b ttyze || echo "not a block dev"
   not a block dev                                               
   fredchen@fredchen:/dev$ test -b sda && echo "it is a block dev"
   it is a block dev
  
   test ! x file  //! 用于条件求反,当file不具x属性时,返回true
3. [] 同样可以用于条件判断
   read -p  "please make your choice: " choice                  
                                                             
   [ "$choice" == "y" ] && echo "you accept it!" &&  exit 0     
   [ "$choice" == "n" ] && echo "you reject it!" &&  exit 0     
   echo "we can not determine your choice!" && exit 0           

 

4. shell script的默认变量 $0 $1 $2 $3 ...

  $0 = script name   
   $1 = para1
   $2 = para2
   
5. if判断
   if [ expression1 ] || [ expression2 ]; then   //semicolon and then
      statement1   //no semiconlon
      statement2   //no semiconlon
   fi
   
   if [ expression1 ] && [ expression2 ]; then  //semicolon and then
      statement1   //no semiconlon
      statement2   //no semiconlon   
   else [ expression1 ] || [ expression2 ]; then  //semicolon and then
      statement3   //no semiconlon
      statement4   //no semiconlon
   fi
   
   
   if [ expression1 ] && [ expression2 ]; then  //semicolon and then
      statement1   //no semiconlon
      statement2   //no semiconlon   
   elif [ expression1 ] || [ expression2 ]; then  //semicolon and then
      statement3   //no semiconlon
      statement4   //no semiconlon
   else
      statement3   //no semiconlon
      statement4   //no semiconlon
   fi   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值