shell 笔记 之控制结构

RobinLiew 2012-10-17

if 语句:

#!/bin/bash

# if 语句格式:
# if 和then放在不同行,并使else和结束处必须的fi与它们水平对齐
if [ "${1}" = '' ]
then
    echo no argument input .
else
    echo first argument is : $1
fi


var=2
echo "${var}"


if [ "${var}" = "1" ]
then 
    echo one .
elif [ "${var}" = "2" ]
then
    echo two .
elif [ "${var}" = "3" ]
then
    echo three .
else
    echo at least four .
fi

for循环:

#!/bin/bash

# in 关键字后面是字列表,
for x in one two three four
do
    echo number $x
done


for var in "$@"
do
    echo you pass in $var
done


# 使用文件通配符
for myfile in /etc/r*
do
    if [ -d "$myfile" ]
    then
        echo "$myfile is dir"
    else
        echo "$myfile"
    fi
done

# 还可以在字列表中使用多个通配符,甚至是变量
# 可以使用相对路径或绝对路径;对于相对路径,bash是相对于当前工作目录执行通配符扩展。
for x in ./*  var/lo* /home/${USER}/*
do
    echo $x
done
 

while和until 循环:

#!/bin/bash

echo use while loop control .
myvar=0
while [ $myvar -ne 10 ]
do
    echo $myvar
    myvar=$(( $myvar + 1 ))
done


echo  
echo  
echo use until loop control .
myvar=10
until [ $myvar -eq 0 ]
do
    echo $myvar
    myvar=$(( $myvar - 1 ))
done
 

相关推荐

onetozero / 0评论 2020-01-08