有没有一种方法可以检查bash脚本是否完整? [英] is there a way to check if a bash script is complete or not?

查看:80
本文介绍了有没有一种方法可以检查bash脚本是否完整?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实施 REPL(已读-eval-print循环).如果已经存在这样的东西,请忽略以下内容,并使用指向它的指针来回答这个问题.

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.

让我们以该脚本为例(将其命名为test.sh):

Let's use this script as an example (name it test.sh):

if true
then
  echo a
else
  echo b
fi
echo c

我要做的是逐行阅读此脚本,检查到目前为止我是否阅读的是完整的bash表达式;如果完成,请eval;否则请继续阅读下一行.下面的脚本有望说明我的想法(尽管效果不佳).

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

动机

对于bash脚本,我想将其解析为语法完整的表达式,评估每个表达式,捕获输出,最后标记源代码和输出(例如,使用Markdown/HTML/LaTeX/...).例如,对于脚本

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
```

推荐答案

bash -n -c "$command_text"

...将确定您的$command_text是否为语法有效的脚本,而无需实际执行.

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

请注意,语法有效"和正确"之间有很大的距离.如果要正确解析语言,请考虑采用类似 http://shellcheck.net/之类的方法.

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.

这篇关于有没有一种方法可以检查bash脚本是否完整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆