Linux学习笔记(9)之Shell编程入门--判断语句

语法一:

if [ 条件表达式 ]

then

命令序列 1

else

命令序列 2

fi

语法二:

if [ 条件表达式 ]; then

命令序列

fi

语法三:

if test 条件表达式 1

then

命令序列 1

elif [ 条件表达式 2 ]

then

命令序列 2

else

命令序列 3

fi

编写shell脚本时,注意条件表达式与“[“ ”]“之间的空格


实例分析:
#!/bin/bash
#script4-1.sh
var1="welcome to use Shell script"
echo $var1
pwd
ls -i

#判断当前目录下是否存在某文件
#!bin/bash
#script4-2.sh
echo "Enter a filename"
read file
if [-f $file]
then
        echo "File $file exists."
fi

#判断当前用户名和输入的用户名是否一致
#!/bin/bash
#script4-3.sh
echo -n "Enter your login name:"
read name
if test "$name" = "$USER"
then
        echo "Hello,$name"
else
        echo "You're not $USER"
fi

#比较两个数的大小
#!/bin/bash
#script4-4.sh
echo "Enter the first integer:"
read first
echo "Enter the second  integer:"
read second
if test "$first" -gt "$second"
    then
        echo "$first is greater than $second"
    elif test "$first" -lt "$second"
    then
        echo "$first is less than $second"
    else
        echo "$first is equal to $second"
fi


#判断myfile文件中是否含有“GNU“字符串
#!/bin/bash
#script4-5.sh
if grep "GNU" myfile >/dev/null
then
    echo "\"GNU\" occurs in myfile"
else
echo
echo "\"GNU\"does not  occurs in myfile"
fi





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值