title: bash and readline: tab completion in a user input loop?
body: <p>I'm making a bash script which presents a command line to the user.</p>
  
  <p>The cli code is as this:</p>
  
  <pre><code>#!/bin/bash
  
  cmd1() {
      echo $FUNCNAME: "$@"
  }
  
  cmd2() {
      echo $FUNCNAME: "$@"
  }
  
  cmdN() {
      echo $FUNCNAME: "$@"
  }
  
  __complete() {
      echo $allowed_commands
  }
  
  shopt -qs extglob
  
  fn_hide_prefix='__'
  allowed_commands="$(declare -f | sed -ne '/^'$fn_hide_prefix'.* ()/!s/ ().*//p' | tr '\n' ' ')"
  
  complete -D -W "this should output these words when you hit TAB"
  
  echo "waiting for commands"
  while read -ep"-&gt; "; do
      history -s $REPLY
      case "$REPLY" in
          @(${allowed_commands// /|})?(+([[:space:]])*)) $REPLY ;;
          \?) __complete ;;
          *) echo "invalid command: $REPLY" ;;
      esac
  done
  </code></pre>
  
  <p><em>Clarification: made and tested in Bash <strong>4</em></strong></p>
  
  <p>So, "read -e" gives readline capabilities, i can recall commands, edit the input line, etc. <strong>What i cannot do in any way</strong> is to have readline's tab completion to work!!</p>
  
  <p>I tried two things:</p>
  
  <ol>
  <li><p>How it should be supposedly done: using the bash builtins "complete" and "compgen", which is reported to work <a href="http://www.linuxquestions.org/questions/programming-9/bash-script-using-tab-complete-473112/#post2609565" rel="noreferrer">here</a> <em>Update: it's not reported to work in scripts</em>.</p></li>
  <li><p><a href="http://www.linuxquestions.org/questions/linux-general-1/commandline-autocompletion-for-my-shell-script-668388/" rel="noreferrer">This ugly workaround</a></p></li>
  </ol>
  
  <p>Why doesn't readline behave correctly when using "complete" inside the script? it works when i try it from bash in interactive mode...</p>