Skip to content
Advertisement

using for in loop with sql output

I have a roles.txt file that contains

admin
user

SELECT ROLE_NAME FROM SENTRY_ROLE WHERE ROLE_NAME produces:

admin

Im trying to echo all the roles from roles.txt that are not in the sql_output (user in this example). This is what i have so far:

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

Advertisement

Answer

That’s not how you iterate over the lines of a file. See http://mywiki.wooledge.org/BashFAQ/001

I would do this, with a single mysql call:

# 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") )

See http://manpages.ubuntu.com/manpages/bionic/en/man1/comm.1.html

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement