[shell脚本]条件判断和循环

本文详细介绍了Shell脚本的基础语法,包括条件判断和循环结构的使用方法,通过实例展示了如何进行数值、字符串判断及文件检测,并提供了数字、字符串、文件路径循环的示例,适合初学者快速掌握Shell脚本编程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本语法

1、条件判断

if [ condition1 ];then
    command 1
elif [ condition2 ];then
    command 2
else
    command3
fi

写成一行:if [ condition ]; then command; fi
注意:
(1)if .. fi标志着判断语句的开始和结束;
(2)[ ]是条件判断符,注意条件语句和判断符首末都需要空出一格;

2、循环
for循环

for var in item1 item2 item3;
do    
    command1
    command2
done

类C风格for循环

for((i=0;i<3;i++));
do
    command1
    command2
done

更详细的参考:
shell流程控制:http://www.runoob.com/linux/linux-shell-process-control.html
shell循环:https://www.jianshu.com/p/f973002a7ca2

实例

1、判断
(1)数值判断
1254006-20181105142401974-50246831.png

#保证脚本传入参数个数正确再执行后面部分
if [ $# -lt 3 ];then
    echo "lack parameters!"
    exit 1
fi

(2)字符串判断
1254006-20181105143323835-977994430.png
(3)文件检测
1254006-20181105143403442-541831629.png

if [ -s ../work/file1 && -s ../work/file2 ];then
    python run.py
    if [ ${?} -eq 0 ];then
        exit 0
    else
        echo "error"
        exit 1
    fi
fi

2、循环
(1)数字循环

sum=0
for i in  {1..19}; do
    $sum = $sum + $i
    echo "sum=$sum"
done

(2)字符串循环

list = "Hello world! "
for i in $list;
do
    echo $i
done

(3)文件路径循环

for file in /home/doc/shell/*.sh
do
    echo $file
done

(4)用循环实现多条类似命令并行

FILE_LIST="file1 file2 file3 ";
for $file in $FILE_LIST;
do
{
    $HADOOP fs -cat $HADOOP_OUT/$file/* > localpath/$file.txt
}
done
wait

说明:haodoop fs -cat命令需要花费一定的时间,因此当需要cat多个路径下的文件时,可以通过for循环让它们并行节省时间,wait命令保证for循环中的命令都执行完后,再执行后续部分。

转载于:https://www.cnblogs.com/surimj/p/9885264.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值