is there a way to check if a bash script is complete or not?

bash, read-eval-print-loop, shell

Solution

bash -n -c "$command_text"

...will determine whether your `$command_text` is a syntactically valid script without actually executing it.

Note that there's a huge breadth of space between "syntactically valid" and "correct". Consider adopting something like http://shellcheck.net/ if you want to properly parse the language.

Problem

I'm trying to implement a REPL (read-eval-print loop) in bash. If such a thing already exists, please ignore the following and answer this question with a pointer to it. Let's use this script as an example (name it `test.sh`): ``` if true then echo a else echo b fi echo c ``` 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, `eval` it; otherwise keep on reading the next line. The script below illustrates my idea hopefully (it does not quite work, though). ``` 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>/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 < test.sh ``` Motivation 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 ``` echo a echo b ``` What I want to achieve is the output like this: ```` ```bash echo a ``` ``` a ``` ```bash echo b ``` ``` b ``` ```` instead of evaluating the whole script and capture all the output: ```` ```bash echo a echo b ``` ``` a b ``` ````

Original source