首页 > 解决方案 > 在循环中使用带有 sql 输出的 for

问题描述

我有一个 roles.txt 文件,其中包含

admin
user

SELECT ROLE_NAME FROM SENTRY_ROLE WHERE ROLE_NAME 产生:

admin

我试图回显roles.txt中不在sql_output中的所有角色(本例中的用户)。这是我到目前为止所拥有的:

for filename in roles.txt
do
sql_output=$(mysql -N -e "SELECT ROLE_NAME FROM SENTRY_ROLE WHERE ROLE_NAME = '$filename';") 


if [ -z "$sql_output" ]
then
  echo "sql_output is empty" #this is where i want to echo all the roles that are not in the output of sql_output AKA "user"
else
  echo "\$sql_output is in sql_output"
  fi
done

标签: linuxbashfor-loopif-statement

解决方案


这不是您遍历文件行的方式。见http://mywiki.wooledge.org/BashFAQ/001

我会这样做,只需一个 mysql 调用:

# Iassume this does not produce any extraneous output,
# just a list of role names, one per line
sql_output=$( mysql -N -e "SELECT distinct ROLE_NAME FROM SENTRY_ROLE" ) 

missing_roles=$( comm -23 roles.txt <(echo "$sql_output") )

请参阅http://manpages.ubuntu.com/manpages/bionic/en/man1/comm.1.html


推荐阅读