Shell 用于从多个 Hive 数据库中的所有 Hive 表中提取行数的脚本

Shell script to pull row counts from all Hive tables in multiple Hive databases

我正在尝试创建一个 shell 脚本,它将从多个数据库中提取所有 table 中的行数。所有数据库都遵循相同的命名约定“the_same_databasename_<%>”,但名称中的最后一层除外,后者有所不同。我正在尝试 运行 以下内容:

use <database_name>; show tables; select count(*) from <table_name>;

因为我有 40 个不同的数据库,我需要 运行 每个数据库的前两个查询 40 次不同的时间,再加上 select 计数查询甚至更多,具体取决于有多少 table 在数据库中(非常耗时)。我将 PuTTy 配置设置设置为将 PuTTy 会话保存到本地目录中的 .txt 文件中,这样我就可以在命令行界面中显示行计数结果。到目前为止,这是我所拥有的,但不确定如何包含最终命令以从每个数据库中的 tables 获取实际行数。

#!/bin/bash
for db in $(hive -e "show databases like 'the_same_databasename_*;") 
do
   tbl_count=$(hive -S -e "use $db; show tables;" | wc -l)
   echo "Database $db contains $tbl_count tables."
  
done    

我在 shell 脚本方面不是很有经验,所以非常感谢任何 guidance/help。提前致谢。

您可以使用嵌套 for 循环:

#!/bin/bash
for db in $(hive -e "show databases like 'the_same_databasename_*;") 
do
   tbl_count=$(hive -S -e "use $db; show tables;" | wc -l)
   echo "Database $db contains $tbl_count tables."

   for table in $(hive -S -e "use $db; show tables;")
   do
      count=$(hive -S -e "use $db; select count(*) from $table;")
      echo "Table $db.$table contains $count rows."
   done
   
done

或者您可以使用变量来增加表的数量

#!/bin/bash
for db in $(hive -e "show databases like 'the_same_databasename_*;") 
do

   tbl_count=0
   for table in $(hive -S -e "use $db; show tables;")
   do
      (( tbl_count++ ))
      count=$(hive -S -e "use $db; select count(*) from $table;")
      echo "Table $db.$table contains $count rows."
   done
   echo "Database $db contains $tbl_count tables."
   
done