Advertisement
shyl-sml178

Untitled

Mar 17th, 2017
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. help() {
  4. cat << EOF
  5. Usage: sql [--type=TYPE] FILENAME [--suffix-curdate] [OPTIONS]
  6. Execute sql query and output result to stdout or file (html/text)
  7. type html, txt or stdout. Default stdout
  8. FILENAME filename to generate html or text
  9. --suffix-curdate add to name current date
  10. OPTIONS See in open-html-file-in-browser.sh
  11. --help print this help
  12.  
  13. For html format:
  14. --delonexit delete generated html file on exit from script
  15. --openinbrowser open generated html in browser
  16. EOF
  17. }
  18.  
  19. if [[ "$@" == *"--help"* ]]; then
  20. help
  21. exit 0
  22. fi
  23.  
  24. sql=$1
  25.  
  26. if [ -z "$sql" ]; then
  27. echo "Missing sql query"
  28. help
  29. exit 1
  30. fi
  31.  
  32. shift 1
  33. filename=
  34. ext=
  35. type=stdout
  36. args=
  37. openinbrowser=0
  38. delonexit=0
  39. withCarDate=0
  40.  
  41. for arg in "$@"; do
  42. case $arg in
  43. --type=*)
  44. type=${arg#*=}
  45. ;;
  46. --filename=*)
  47. filename=${arg#*=}
  48. ;;
  49. --openinbrowser)
  50. openinbrowser=1
  51. ;;
  52. --delonexit)
  53. delonexit=1
  54. ;;
  55. --suffix-curdate)
  56. withCarDate=1
  57. ;;
  58. *)
  59. echo "Unknown argument: $arg"
  60. help
  61. exit 1
  62. ;;
  63. esac
  64. done
  65.  
  66. isStdOut=0; [ "$type" == "stdout" ] && isStdOut=1
  67. isHtml=0; [ "$type" == "html" ] && isHtml=1
  68.  
  69. if [ $isHtml == 1 ]; then
  70. ext="html"
  71. args=" -H"
  72. elif [ "$type" == "txt" ] ; then
  73. ext="txt"
  74. args=" "
  75. fi
  76.  
  77. if [ $isStdOut != 1 ] && [ -z "$ext" ]; then
  78. echo "Invalid TYPE"
  79. help
  80. exit 1
  81. fi
  82.  
  83. if [ $isStdOut == 0 ] && [ -z "$filename" ]; then
  84. echo "Missing FILENAME"
  85. help
  86. exit 1
  87. fi
  88.  
  89. if [ $withCarDate == 1 ]; then
  90. filename+=_$(date +"%Y.%m.%d_%H-%M-%S")
  91. fi
  92.  
  93. echo "SQL: $sql"
  94.  
  95. if [ $isStdOut == 1 ] ; then
  96. mysql-car -e "$sql;"
  97. else
  98. filename+=.$ext
  99. mysql-car -e "$sql;" $args > $filename
  100. echo "Query saved to $filename."
  101.  
  102. if [ $isHtml == 1 ]; then
  103. args=""
  104.  
  105. if [ $delonexit == 1 ]; then
  106. args+="--delonexit"
  107. fi
  108.  
  109. args+=" "
  110.  
  111. if [ $openinbrowser == 1 ]; then
  112. args+="--openinbrowser"
  113. fi
  114.  
  115. $(dirname "$0")/open-html-file-in-browser.sh $filename $args
  116. fi
  117. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement