shell实操1-在shell脚本内连接hive做sql查询

相关知识点

shell的循环;shell连接hive-hive语句执行、hive文件执行;传参;输入输出文件,文件删除

shell中list的循环:

for line in ${list[@]}   #这里不能只写${list},执行结果不对,回头测试一下
do
    执行语句
done

shell中的判断:

result=$?
if [$result !=0 ]; then
    执行语句
fi

cat配合重定向生成文件

cat << EOF >/path/filename    # 也可以使用>>对文件进行追加
your content
EOF                              #顶格写

EOF只是一个分界符,当然也可以用abcde替换。

当shell遇到<<时,它知道下一个词是一个分界符。在该分界符以后的内容都被当作输入,直到shell又看到该分界符(位于单独的一行)。

通过cat配合重定向能够生成文件并追加操作。

代码

代码一

场景:有一批平行的数据库db1, db2, db3, ...,每个库都有tb_name这张表,现在要对每个库的这张表执行查询操作,通过shell后台连接hive数据库可以批量处理

#!/bin/bash
db_list=("db1" "db2" "db3" "db4" "db5" "db6")
hive_url='jdbc:hive2://...;principal=hive/...'   #通过jdbc连接hive
for db in ${db_list[@]}                                  
do
    echo "${db}"
    beeline -u "${hive_url}"  --silent=false -hivevar db=$db -e "hivesql查询语句,eg: select * from ${db}.tb_name limit 1"
done                                                   #这里silent静默模式若设置为True,会省略MR日志
#判断上一条是否成功
result=$?
if [$result !=0 ]; then
    echo "---------------错误码:status:$result--------------------------"
fi

将hivesql放在文件中,用文件方式操作

#这里文件通过循环追加文本存储的是参数还是参数值?           ——是参数值

#!/bin/bash
db_list=("db1" "db2" "db3" "db4" "db5" "db6")
path=/home/luxia
for db in ${db_list[@]}
do
    cat <<EOF >>${path}/tmp.hql
        select * from ${db}.tb_name;
EOF
done
>cat tmp.hql        
        select * from db1.tb_name;
        select * from db2.tb_name;
        select * from db3.tb_name;
        select * from db4.tb_name;
        select * from db5.tb_name;
        select * from db6.tb_name;

 代码二

#!/bin/bash
path=/home/username/...
db_list=("db1" "db2" "db3" "db4" "db5" "db6")
hive_url='jdbc:hive2://...;principal=hive/...'   #通过jdbc连接hive
db_list=("db1" "db2" "db3" "db4" "db5" "db6")

for db in ${db_list[@]}
do
    cat <<EOF >>${path}/tmp.hql
        select * from ${db}.tb_name;    
EOF                                        
done                                              #循环拼接sql

hql=${path}/tmp.hql
beeline -u "${hive_url}" --silent=false [-hivevar var1=${var1}] -f $hql        #文件调用

rm -f $hql
原文地址:https://www.cnblogs.com/foolangirl/p/14132120.html