linux shell 之结构化语法

一、case分支语句

 

     语法格式:     

case $变量名 in
                模式1)
            命令序列1
            ;;

                模式2)
            命令序列2
            ;; 

                *)
            默认执行的命令序列     
            ;; 
            
           esac 

    case代码实例

 

#!/bin/bash
read -p "press some key ,then press return :" KEY
case $KEY in
[a-z]|[A-Z])
echo "It's a letter."
;;
[0-9]) 
echo "It's a digit."
;;
*)
echo "It's function keys、Spacebar or other ksys."
;;
esac

 

其中read -p 是从控制台读取字符串

 

二、if分支

 

语法格式

    

if command
then
    commands
fi

或者
if command:then
    commands
fi

或者
if command
then
    commands
else
    commands
fi

或者

if command1
then
    commands
elif command2
then
     commands
fi

 

   test命令语法

   

if test condition
then
   commands
fi

或者

if [condition]
then
   commands
fi

 

    test数值的比较

    n1 -eq n2                        检查n1是否与n2相等

    n1 -ge n2                        检查n1是否大于等于n2

    n1 -gt n2                          检查n1是否大于n2

    n1 -le n2                          。。。。。

    n1 -lt n2                           。。。。。

    n1 -ne n2                         。。。。。。

 

    test字符串比较

    str1 = str2

    str1 != str2

    str1 < str2                  

    str1 > str2

    -n str1                       检查str1的长度是否非0

    -z str1                        检查str1的长度是否为0

    注意,使用的时候<或者 >需要转义\

 

    代码实例

   

#!/bin/bash
var1=10
var2=11

if [ $var1 -gt 5 ]
then
  echo "The test value $var1 is greater than 5"
fi

if [ $var1 -eq $var2 ]
then
  echo "The values are equal"
else
  echo "The valus are fifferent"
fi

运行结果:
The test value 10 is greater than 5
The valus are fifferent


需要注意的是[]左右内侧必须有空格,否则运行报错

 

   三、文件比较

    比较描述
-d file检查file是否存在并是一个目录
-e file检查file是否存在
-f file检查file是否存在并是一个文件
-r file检查file是否存在并可读
-s file 检查file是否存在并非空
-w file检查file是否存在并可写
-x file检查file是否存在并可执行
-O file检查file是否存在并属于当前用户所有
-G file检查file是否存在并且默认组与当前用户相同
file1 -nt file2检查file1是否比file2新
file1 -ot file2检查file1是否比file2旧

   

  代码实例

  

#!/bin/bash
if [ -e $HOME ]
then
   echo "home exist"
else
   echo "home not exist"
fi

 

四、for语法

 

for var in list
do 
  commands
done

 

    实例

    

#!/bin/bash
for var in Alaska Ae we wer
do
  echo the next state is $var
done

运行结果:
$ sh fortest.sh
the next state is Alaska
the next state is Ae
the next state is we
the next state is wer

 

   解析文本文件,并循环输出文件内容

   

#!/bin/bash
IFS.OLD=$IFS
IFS=$'\n'
for entry in `cat /etc/passwd`
do
  echo "values in $entry"
  IFS=:
  for value in $entry
  do
    echo "   $value"
  done
done

IFS=$IFS.OLD

 

 

  while,until,..

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值