martes, 30 de diciembre de 2014

Mysql query resultset in bash script

http://unix.stackexchange.com/questions/111545/mysql-query-resultset-in-bash-script



mysql seems to output the results to a shell variable in a single line. One way round this is to write the contents to a temporary file, then process in a while loop.
EDIT On my system IFS="\n" before the mysql command (when the results are assigned to a shell variable) gives the correct multi-line output. e.g.
 IFS="\n"
 Total_results=$(mysql.....)
=============== End of Edit ==========================
#!/bin/bash
mysql --silent -h server-name -P 3306 -u username-ppassword -D dbname<<<"select URL  from Experiment where URL_Exists = 1" > tmp_results

while read URL
do 
   echo $URL
   var=$(curl -s --head $URL | head -n 1 | grep "HTTP/1.[01] [23]..")
   echo "$var"
   if [ -z "$var" ]
   then
     echo "Ok we do not have a valid link and the value needs to be updated as -1 here"
   else
     echo "we will update the value as 1 from here"
   fi
done < tmp_results
 
 
 
-------------------------------------- 
You don't need a variable or a temp file for this, just parse the mysql command directly by piping to the while loop:
#!/bin/bash
mysql <<<"select URL from Experiment where URL_Exists = 1" |

while IFS='\n' read URL
do
  echo $URL
  var=$(curl -s --head $URL | head -n 1 | grep "HTTP/1.[01] [23]..")
  echo "$var"
  if [ -z "$var" ]
  then
    echo "Ok we do not have a valid link and the value needs to be updated as -1 here"
  else
    echo "we will update the value as 1 from here"
  fi
done
 
 
 
 
 

0 comentarios:

Publicar un comentario

Suscribirse a Enviar comentarios [Atom]

<< Inicio