shell编程-条件判断与流程控制

1.条件判断式

按照文件类型进行判断:

两种判断格式:

test -e /root/install.log

[ -e /root/install.log ]

判断命令是否正确执行:

[ -d /root ] && echo "yes" || echo "no"

按文件权限判断:

两个文件之间的比较:

[ /root/stu.txt -ef /tmp/stu.txt]

两个整数之间的比较:

字符串的判断:

a=21,b=56

[ "$a" == "$b" ]

多重条件的判断:

2.流程控制

单分支语句if:

判断登陆用户是否为root:

vim isRoot.sh

#!/bin/bash

test=$(env | grep USER |cut -d "=" -f 2)

if [ "$test" == "root"];then

  echo "the user is root"

fi

双分支if语句:

read -t 30 -p "please enter a dir: "dir

if [ -d "$dir" ]

  then

    echo "is dir"

  else

    echo "no"

fi

判断Apache是否启动

test=$(ps aux | grep httpd |grep -v grep)

if [ -n "$test" ] 

  then

    echo "$(date) httpd is running"

  else

    echo "httpd is not running"

    services httpd start

fi

多分支if语句:

多分支case语句:

for循环:

cd /root/test/

ls *.tar.gz > ls.log

ls *.tgz >> ls.log

for i in $( cat ls.log )

  do

    tar -zxf  $i & > /dev/null

  done

rm -rf ls.log

for i in $(cat /etc/passwd | grep /bin/bash |grep -v root |cut -d ":" -f1)

  do 

    userdel -r $i

  done

while循环和until循环:

原文地址:https://www.cnblogs.com/Nyan-Workflow-FC/p/5669012.html