Is Bash compiled or interpreted? Is Bash compiled or interpreted? shell shell

Is Bash compiled or interpreted?


Bash is a single-pass interpreter which means it reads one command at a time, interprets, and runs it then and there. The same thing is true with other types of shells - sh, ksh, zsh, csh, etc.

Here is an example. I have a 3 line script called test.sh which looks like this:

echo oneecho two'

When run as bash test.sh, it gives this output:

onetwotest.sh: line 3: unexpected EOF while looking for matching `''test.sh: line 4: syntax error: unexpected end of file

It runs the first and second commands successfully and then encounters the dangling single quote and throws the error.

Let's say we write the same code in Perl, test.pl:

print "one\n"print "two\n"'

and run it with perl test.pl. We get:

syntax error at test.pl line 2, near "print"Can't find string terminator "'" anywhere before EOF at test.pl line 3.

So, it didn't run the first two lines at all, though they were syntactically correct. That's because Perl makes two passes. In the first pass, it does syntax checks and converts the script into an internal form. In the second pass, it runs it.

The simplicity of shell's single-pass execution is its biggest limitation as well. Tolerating syntax errors, even running at all, makes it hard to build large and robust code with the shell language. However, shell scripting is an ideal choice for quick and throw-away code, especially something that makes use of a lot of command line utilities.


Related:


The bash shell, as it stands now (version 4.4), runs your scripts in a purely textual fashion. It does not do any pre-compilation of files into some form of byte code.

As per the source code, the shell itself just uses reader_loop() to process the input. This calls, within a loop, read_command() followed by execute_command().

As the read_command() also contains the call to parse_command() which calls the YACC parser function yyparse(), this means that parsing happens on a line-by-line basis, not up front in some large compilation phase.


Another way to see that bash processes its input one line at a time is to create a script with an obvious syntax error after a valid echo statement, then run the script. bash will produce some output before producing a syntax error:

echo output()

produces

$ bash tmp.shoutputtmp.sh: line 2: syntax error near unexpected token ')'tmp.sh: line 2: `()'