shell脚本中用hive -e执行sql出现「cannot recognize input near ‘<EOF>‘ in select clause」问题

问题现象

写了一个简单的shell脚本调用hive执行组装的sql,在执行时总是报cannot recognize input near '' in select clause错误,
单独在hive提示符下却能正常执行。

#!/bin/bash
keyname="type"
sql=" 
select tags['$keyname'] from user_tags
"

echo ${sql}

hive -e ${sql}

具体报错如下:

Logging initialized using configuration in file:/data/sysdir/servers/hive-2.0.1-bin-3.2.1-20211230/conf/hive-log4j2.properties
NoViableAltException(-1@[])
    at org.apache.hadoop.hive.ql.parse.HiveParser_SelectClauseParser.selectClause(HiveParser_SelectClauseParser.java:1115)
    at org.apache.hadoop.hive.ql.parse.HiveParser.selectClause(HiveParser.java:47987)
    at org.apache.hadoop.hive.ql.parse.HiveParser.selectStatement(HiveParser.java:42231)
    at org.apache.hadoop.hive.ql.parse.HiveParser.regularBody(HiveParser.java:42138)
    at org.apache.hadoop.hive.ql.parse.HiveParser.queryStatementExpressionBody(HiveParser.java:41154)
    at org.apache.hadoop.hive.ql.parse.HiveParser.queryStatementExpression(HiveParser.java:41024)
    at org.apache.hadoop.hive.ql.parse.HiveParser.execStatement(HiveParser.java:1653)
    at org.apache.hadoop.hive.ql.parse.HiveParser.statement(HiveParser.java:1137)
    at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:204)
    at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:166)
    at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:440)
    at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:319)
    at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1249)
    at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1295)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1178)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1166)
    at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:236)
    at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:187)
    at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:403)
    at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:339)
    at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:748)
    at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:721)
    at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:648)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:323)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:236)
FAILED: ParseException line 1:6 cannot recognize input near '' '' '' in select clause
 

解决方案

修改hive -e ${sql}hive -e "${sql}"

原因分析

若没有使用双引号进行包括,则"hive -e"会认为后面的sql内容解析为多个参数造成错误。而使用双引号后,整个sql将作为一个单独的参数传给hive。

你可能感兴趣的:(Linux,hive,hive,bash)