美文网首页
Shell学习

Shell学习

作者: _XueW | 来源:发表于2019-08-19 10:46 被阅读0次

    前言

    Shell 是一个用 C 语言编写的程序,它是用户使用 Linux 的桥梁。Shell 既是一种命令语言,又是一种程序设计语言。
    Shell 脚本(shell script),是一种为 shell 编写的脚本程序。
    Shell 编程跟 JavaScript、php 编程一样,只要有一个能编写代码的文本编辑器和一个能解释执行的脚本解释器就可以了。
    Linux 的 Shell 种类众多,常见的有:

    • Bourne Shell(/usr/bin/sh或/bin/sh)
    • Bourne Again Shell(/bin/bash)
    • C Shell(/usr/bin/csh)
    • ...

    练习

    #!/bin/bash
    #练习1:1+2+...+99+100求和
    num=1
    sum=0
    while [ $num -le 100 ]
    do
    sum=`expr $sum + $num`
    num=`expr $num + 1`
    done
    echo "1+2+...+99+100=$sum"
    

    实践

    最近需要更新车辆定位数据的历史表中的坐标系(WGS-84转换为GCJ-02),由于历史数据表都是千万级别的大表,故选择批处理的方式进行更新,使用sql中的limit进行分页,每页中处理100W条记录,python脚本中只需要传入表名、起始页码和偏移量即可,再利用shell脚本自动执行。话不多说,上代码。

    1. Python脚本
    #!/usr/bin/env python3
    import time,click
    from gpsInterface import getExistData,insertDB,gpsCoordinateTrans
    
    def gpsTransfer(dfs):
        lng1, lat1 = [], []  # 保存GCJ-02坐标系经纬度
        lng, lat = dfs['lon'].tolist(), dfs['lat'].tolist()
        for i in range(len(lng)):
            templng1, templat1 = gpsCoordinateTrans.wgs84_to_gcj02(float(lng[i]), float(lat[i]))
            lng1.append(templng1)
            lat1.append(templat1)
        return lng1, lat1
    
    @click.command()
    @click.option("--table")
    @click.option("--pstart", type=int)
    @click.option("--pstep",  type=int)
    def runUpdate(table, pstart, pstep):
        startTime = time.time()
        dfs = getExistData.getHisData(table, pstart, pstep)
        lng1,lat1 = gpsTransfer(dfs)
        dfs['lng1'] = lng1
        dfs['lat1'] = lat1
        new_col = ['id', 'lng', 'lat', 'lng1', 'lat1']
        dfs.columns = new_col
    
        if insertDB.updateDB(table, data=dfs):
            print('[INFO] Successfully update lng1,lat1 in {0} from rows {1} to {2}.'.format(table,pstart,pstart+pstep))
        endTime = time.time()
        print('[INFO] Run times: %.8s s.' % (endTime-startTime))
    
    if __name__ == "__main__":
       runUpdate()
    
    1. Shell脚本
    #!/bin/bash
    cd /tdpdata/redis/script/python/gpsdata
    echo `pwd`
    
    num=0
    # 这里的27是页码总数
    while [ $num -le 27 ]
    do
    # 注意这里使用expr进行乘法运算时的坑,乘号 '*' 前必须加上反斜杠 '\',否则会报参数错误
    pageStart=`expr $num \* 1000000`
    echo "Num = $num, pageStart from $pageStart"
    # 执行python命令
    /usr/local/bin/python3 updateCoor.py --table gps_car_location_his_201910 --pstart $pageStart --pstep 1000000 &>> /tdpdata/redis/script/python/gpsdata/logs/updateCoor.log
    # 页码自增
    num=`expr $num + 1`
    done
    

    参考资料

    Shell | 菜鸟教程
    Linux Shell脚本学习指南

    相关文章

      网友评论

          本文标题:Shell学习

          本文链接:https://www.haomeiwen.com/subject/jbtssctx.html