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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM