Advertisement
Guest User

bash sqlite history

a guest
Sep 8th, 2015
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.56 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. source "$BASHSOURCEDIR"/*-bash-preexec.sh
  4.  
  5. # header guard
  6. [ -n "$_SQLITE_HIST" ] && return || readonly _SQLITE_HIST=1
  7.  
  8. HISTDB="$HOME/.hist.db"
  9. HISTSESSION=`dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64`
  10.  
  11. __quote_str() {
  12.     local str
  13.     local quoted
  14.     str="$1"
  15.     quoted="'$(echo "$str" | sed -e "s/'/''/g")'"
  16.     echo "$quoted"
  17. }
  18. __create_histdb() {
  19.     if bash -c "set -o noclobber; > \"$HISTDB\" ;" &> /dev/null; then
  20.         sqlite3 "$HISTDB" <<-EOD
  21.         CREATE TABLE command (
  22.             command_id INTEGER PRIMARY KEY,
  23.             shell TEXT,
  24.             command TEXT,
  25.             cwd TEXT,
  26.             return INTEGER,
  27.             started INTEGER,
  28.             ended INTEGER,
  29.             shellsession TEXT,
  30.             loginsession TEXT
  31.         );
  32.         EOD
  33.     fi
  34. }
  35.  
  36. preexec() {
  37.     [[ ! -v HISTDB ]] && return 0
  38.     local cmd
  39.     cmd="$1"
  40.  
  41.     #atomic create file if not exist
  42.     __create_histdb
  43.    
  44.     local quotedloginsession
  45.     if [[ -v LOGINSESSION ]]; then
  46.         quotedloginsession=$(__quote_str "$LOGINSESSION")
  47.     else
  48.         quotedloginsession="NULL"
  49.     fi
  50.     LASTHISTID="$(sqlite3 "$HISTDB" <<-EOD
  51.         INSERT INTO command (shell, command, cwd, started, shellsession, loginsession)
  52.         VALUES (
  53.             'bash',
  54.             $(__quote_str "$cmd"),
  55.             $(__quote_str "$PWD"),
  56.             $(date +%s%3N),
  57.             $(__quote_str "$HISTSESSION"),
  58.             $quotedloginsession
  59.         );
  60.         SELECT last_insert_rowid();
  61.         EOD
  62.     )"
  63.  
  64.     echo "$cmd" >> ~/.testlog
  65. }
  66.  
  67. precmd() {
  68.     local ret_value="$?"
  69.     if [[ -v LASTHISTID ]]; then
  70.         __create_histdb
  71.         sqlite3 "$HISTDB" <<- EOD
  72.             UPDATE command SET
  73.                 ended=$(date +%s%3N),
  74.                 return=$ret_value
  75.             WHERE
  76.                 command_id=$LASTHISTID ;
  77.         EOD
  78.     fi
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement