title: is there a way to check if a bash script is complete or not?
body: <p>I'm trying to implement a <a href="http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop" rel="noreferrer">REPL (read-eval-print loop)</a> in bash. If such a thing already exists, please ignore the following and answer this question with a pointer to it.</p>
  
  <p>Let's use this script as an example (name it <code>test.sh</code>):</p>
  
  <pre><code>if true
  then
    echo a
  else
    echo b
  fi
  echo c
  </code></pre>
  
  <p>What I want to do is to read this script line by line, check if what I have read so far is a complete bash expression; if it is complete, <code>eval</code> it; otherwise keep on reading the next line. The script below illustrates my idea hopefully (it does not quite work, though).</p>
  
  <pre><code>x=""
  while read -r line
  do
    x=$x$'\n'$line  # concatenate by \n
    # the line below is certainly a bad way to go
    if eval $x 2&gt;/dev/null; then
      eval $x  # code seems to be working, so eval it
      x=""  # empty x, and start collecting code again
    else
      echo 'incomplete expression'
    fi
  done &lt; test.sh
  </code></pre>
  
  <h2>Motivation</h2>
  
  <p>For a bash script, I want to parse it into syntactically complete expressions, evaluate each expression, capture the output, and finally mark up the source code and output (say, using Markdown/HTML/LaTeX/...). For example, for a script</p>
  
  <pre><code>echo a
  echo b
  </code></pre>
  
  <p>What I want to achieve is the output like this:</p>
  
  <pre><code>```bash
  echo a
  ```
  
  ```
  a
  ```
  
  ```bash
  echo b
  ```
  
  ```
  b
  ```
  </code></pre>
  
  <p>instead of evaluating the whole script and capture all the output:</p>
  
  <pre><code>```bash
  echo a
  echo b
  ```
  
  ```
  a
  b
  ```
  </code></pre>