Advertisement
jaalto

Bash coproc and SQLite

Feb 25th, 2025 (edited)
529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.85 KB | None | 0 0
  1. #! /bin/bash
  2. # Testing 'coproc' feature in Bash with SQLite
  3.  
  4. SQL_DB=${1:-test.db}
  5.  
  6. coproc sqlproc {
  7.     # non-existig file "none" ignores reading ~/.sqliterc
  8.     sqlite3 -init none
  9. }
  10.  
  11. SQL_IN=${sqlproc[0]}
  12. SQL_OUT=${sqlproc[1]}
  13.  
  14.  
  15. Sql ()
  16. {
  17.     local stmt=$1
  18.  
  19.     if [[ $stmt =~ ^\. ]]; then
  20.         : # Skip, SQLite internal ".command"
  21.     elif [[ ! $stmt =~ \;[[:space:]]*$ ]]; then
  22.         # Add missing semicolong
  23.         stmt+=";"
  24.     fi
  25.  
  26.     printf '%s\n' "$stmt" '.shell printf \\0' >&"$SQL_OUT"
  27.     IFS= read -r -d '' -u "$SQL_IN"  # output in $REPLY
  28. }
  29.  
  30.  
  31. SqlClose ()
  32. {
  33.     Sql ".quit"
  34.     wait
  35. }
  36.  
  37. Main ()
  38. {
  39.     Sql ".open $SQL_DB"
  40.     echo "$REPLY"
  41.  
  42.     Sql ".tables"
  43.     echo "$REPLY"
  44.  
  45.     Sql "SELECT * FROM emp;"
  46.     echo "$REPLY"
  47. }
  48.  
  49.  
  50. # Close coproc on exit
  51. trap SqlClose EXIT
  52.  
  53. Main "$@"
  54.  
  55. # End of file
  56.  
Tags: BASH
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement