Hive可以在CLI命令行中执行,但是对于不懂的hive的人会比较麻烦,所以就想能否通过shell去执行hive的语句呢,封装起来只要执行一条shell命令就可以了,每次执行只要自己传入不同参数就可以了,并且如果以后需要做定时器任务crontab也是需要调用shell的,于是就有了下面的学习
1、直接在命令行中执行
hive -e 'create table db.cl_a(a string);create table db.cl_b(b string);'
2、把需要执行的hql单独保存成文件,然后通过linux的命令行执行
hive -f hive-script.sql
也可在Hive shell中执行
source /路径/文件名.hql;
hive-script.sql文件代码如下
use database;
drop table cl_a;
--create table cl_a(a string);
3、结合1、2,把他们放到shell文件中(.sh文件),sh文件等同于在命令行,sh hivesh-test.sh
hivesh-test.sh文件代码
hive -f hive-script.sql
hive -e 'create table db.cl_a(a string);create table db.cl_b(b string);'
4、进阶,比如我在执行sh的时候,想传入参数
(1)通过shell参数传入
hivesh-test.sh文件代码
db=$1
echo ${db}
hive -e 'use db;create table db.'${db}'(a string);create table db.cl_b(b string);'
linux命令行执行如下
sh hivesh-test2.sh cl_a
注意,这种方式不能传参数到一个单独的.sql文件,那怎么办?请往下看,通过下面两种方式可以传入参数
(2)通过hiveconf,hiveconf属于hive-site.xml下面配置的环境变量
hivesh-test.sh文件代码
tb_name=$1
echo ${tb_name}
hive --hiveconf db=${tb_name} -f hive-script.sql
hive-script.sql代码如下
use db;
drop table ${hiveconf:db};
--create table cl_a(a string);
命令行执行的命令如下
sh hivesh-test.sh cl_a
(3)hivevar,hivevar为用户自定义变量
hivesh-test.sh文件代码
tb_name=$1
echo ${tb_name}
hive --hivevar db=${tb_name} -f hive-script.sql
hive-script.sql代码如下
use db;
drop table ${db};
命令行执行如下
sh hivesh-test.sh cl_a