Linux使用结构化命令

目录

1 if结构化命令

2 for结构化命令

3 while结构化命令

4 until迭代语句


1 if结构化命令

if command

then commands

fi(bash shell 会用fi语句在if then之后表示该语句结束)

elif命令检查系统是否有该用户,若有就输出该用户目录下的文件

#!/bin/bash
#testing the else statement
echo "*****************************"
echo "test else satemenr"
user=lys
if grep $user /etc/passwd
then
        echo "$user was found in the system:"
        ls -a /home/$user/.b*
else
        echo "the user $user does not exist on this system."
        echo
fi
echo "***********************"

#if (if)
echo "test the nested if statement"
if grep $user /etc/passwd
then
        echo "the user $user exists on this system:"
        ls -a /home/$user/.b*
else
        echo "the user $user does not exist on this system."
        if ls -d /home/$user/
        then
                echo "However. $user has a directorty."
        fi
fi
echo

2 for结构化命令

创建循环进行遍历

for命令基本格式:

for var in list

do commands

done 

IFS=:
for s in $HOME
do
   echo "$s:"
   for file in $s/*
   do
      if [ -x $file ]
      then
          echo "   $file"
          echo"文件可执行  "
      fi
   done
done

运行结果如下:

3 while结构化命令

当语句符合条件程序继续进行如果状态码不是0的话则终止程序。

while命令基本结构:

while test command

do other commands

done

代码展示

#!/bin/bash
#while command test
echo "***** while command test*****"
var1=5
while [ $var1 -gt 0 ]
do
        echo $var1
        var1=$[ $var1 - 1 ]
done
echo

#using mulriple test command
echo "*****using mutiple test command*****"
var1=5
while echo $var1
        [ $var1 -ge 0 ]
do
        echo "This is inside the loop"
        var1=$[ $var1 - 1 ]
done
echo

运行结果如下:

4 until迭代语句

与while命令不同until语句需要指定一个条件当满足这个条件后退出

until命令基本结构:

until test command

do other commands

done

嵌套循环

打印九九乘法表

y轴循环九次,且打印九行空行

x轴打印与y轴的乘积

#!/bin/bash
y=1
until [ $y -gt 9 ]
do
        x=1
        until [ $x -gt $y ]
        do
                echo -ne "$x*$y=$[ $x*$y ]\t"
                let x++
        done
echo
echo
let y++
done

结果展示:

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值