21

我正在尝试在 bash中实现REPL(读取-评估-打印循环) 。如果这样的事情已经存在,请忽略以下内容并用指向它的指针回答这个问题。

让我们以这个脚本为例(命名它test.sh):

if true
then
  echo a
else
  echo b
fi
echo c

我要做的是逐行阅读这个脚本,检查我到目前为止所阅读的是否是一个完整的bash表达式;如果它是完整的,eval它;否则继续阅读下一行。下面的脚本很有希望地说明了我的想法(虽然它不太有效)。

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/...)。例如,对于脚本

echo a
echo b

我想要实现的是这样的输出:

```bash
echo a
```

```
a
```

```bash
echo b
```

```
b
```

而不是评估整个脚本并捕获所有输出:

```bash
echo a
echo b
```

```
a
b
```
4

4 回答 4

6
bash -n -c "$command_text"

...将在不实际执行的情况下确定您$command_text的脚本是否在语法上有效。


请注意,“语法有效”和“正确”之间有很大的差距。如果您想正确解析语言,请考虑采用类似http://shellcheck.net/的内容。

于 2016-07-25T02:49:17.800 回答
4

以下脚本应生成您期望的 Markdown 输出。

eval "set -n; $x"用于通过检查命令中的语法错误来验证命令是否完整。只有没有语法错误的命令才会被认为是完整的、执行的,并显示在输出 Markdown 中。

请注意,要处理的输入脚本是在子shell中执行的,因此不会干扰处理脚本本身(即输入脚本可以使用与处理脚本相同的变量名,并且不能更改变量的值)在处理脚本中)。唯一的例外是称为 的特殊变量___internal__variable___

两种方法可以实现这一目标,我将在下面介绍。在版本 1中,每当处理一个新的完整命令时,它之前的所有语句都会被执行以创建命令的“上下文”。这有效地多次运行输入脚本。

版本 2中,在执行完每个完整的命令后,子 shell 的环境存储在一个变量中。然后,在执行下一条命令之前,在子shell中恢复之前的环境。

版本 1

#!/bin/bash

x=""  # Current
y=""  # Context
while IFS= read -r line  # Keep indentation
do
    [ -z "$line" ] && continue  # Skip empty lines

    x=$x$'\n'$line  # Build a complete command
    # Check current command for syntax errors
    if (eval "set -n; $x" 2> /dev/null)
    then
        # Run the input script up to the current command
        # Run context first and ignore the output
        ___internal_variable___="$x"
        out=$(eval "$y" &>/dev/null; eval "$___internal_variable___")
        # Generate command markdown
        echo "=================="
        echo
        echo "\`\`\`bash$x"
        echo "\`\`\`"
        echo
        # Generate output markdown
        if [ -n "$out" ]
        then
            echo "Output:"
            echo
            echo "\`\`\`"
            echo "$out"
            echo "\`\`\`"
            echo
        fi
        y=$y$'\n'$line  # Build context
        x=""  # Clear command
    fi
done < input.sh

版本 2

#!/bin/bash

x=""  # Current command
y="true"  # Saved environment
while IFS= read -r line  # Keep indentation
do
    [ -z "$line" ] && continue  # Skip empty lines

    x=$x$'\n'$line  # Build a complete command
    # Check current command for syntax errors
    if (eval "set -n; $x" 2> /dev/null)
    then
        # Run the current command in the previously saved environment
        # Then store the output of the command as well as the new environment
        ___internal_variable_1___="$x"  # The current command
        ___internal_variable_2___="$y"  # Previously saved environment
        out=$(bash -c "${___internal_variable_2___}; printf '<<<BEGIN>>>'; ${___internal_variable_1___}; printf '<<<END>>>'; declare -p" 2>&1)
        # Separate the environment description from the command output
        y="${out#*<<<END>>>}"
        out="${out%%<<<END>>>*}"
        out="${out#*<<<BEGIN>>>}"

        # Generate command markdown
        echo "=================="
        echo
        echo "\`\`\`bash$x"
        echo "\`\`\`"
        echo
        # Generate output markdown
        if [ -n "$out" ]
        then
            echo "Output:"
            echo
            echo "\`\`\`"
            echo "$out"
            echo "\`\`\`"
            echo
        fi
        x=""  # Clear command
    fi
done < input.sh

例子

对于输入脚本input.sh

x=10
echo "$x"
y=$(($x+1))
echo "$y"


while [ "$y" -gt "0" ]
do
    echo $y
    y=$(($y-1))
done

输出将是:

==================

```bash
x=10
```

==================

```bash
echo "$x"
```

Output:

```
10
```

==================

```bash
y=$(($x+1))
```

==================

```bash
echo "$y"
```

Output:

```
11
```

==================

```bash
while [ "$y" -gt "0" ]
do
    echo $y
    y=$(($y-1))
done
```

Output:

```
11
10
9
8
7
6
5
4
3
2
1
```
于 2016-07-25T04:43:36.690 回答
3

假设您的测试命令存储在一个名为“example”的文件中。也就是说,使用与先前答案相同的命令:

$ cat example
x=3
echo "$x"
y=$(($x+1))
echo "$y"


while [ "$y" -gt "0" ]
do
    echo $y
    y=$(($y-1))
done

命令:

$ (echo 'PS1=; PROMPT_COMMAND="echo -n =====; echo"'; cat example2 ) | bash -i

产生:

=====
x=3
=====
echo "$x"
3
=====
y=$(($x+1))
=====
echo "$y"
4
=====

=====

=====
while [ "$y" -gt "0" ]
> do
>     echo $y
>     y=$(($y-1))
> done
4
3
2
1
=====
exit

如果您也对循环的中间结果感兴趣,请使用以下命令:

$ ( echo 'trap '"'"'echo; echo command: $BASH_COMMAND; echo answer:'"'"' DEBUG'; cat example ) | bash

结果是:

command: x=3
answer:

command: echo "$x"
answer:
3

command: y=$(($x+1))
answer:

command: echo "$y"
answer:
4

command: [ "$y" -gt "0" ]
answer:

command: echo $y
answer:
4

command: y=$(($y-1))
answer:

command: [ "$y" -gt "0" ]
answer:

command: echo $y
answer:
3

command: y=$(($y-1))
answer:

command: [ "$y" -gt "0" ]
answer:

command: echo $y
answer:
2

command: y=$(($y-1))
answer:

command: [ "$y" -gt "0" ]
answer:

command: echo $y
answer:
1

command: y=$(($y-1))
answer:

command: [ "$y" -gt "0" ]
answer:

附录 1

将先前的结果更改为其他格式并不难。例如,这个小的 perl 脚本:

$ cat formatter.pl 
#!/usr/bin/perl
#

$state=4; # 0: answer, 1: first line command, 2: more command, 4: unknown

while(<>) {
#  print $state;

  if( /^===COMMAND===/ ) {
    print "===\n";
    $state=1;
    next;
  }

  if( $state == 1 ) {
    print;
    $state=2;
    next;
  }

  if( $state == 2 && /^>+ (.*)/ ) {
    print "$1\n";
    next;
  }

  if( $state == 2 ) {
    print "---\n";
    $state=0;
    redo;
  }

  if( $state == 0 ) {
    print;
    next;
  }
}

在命令中使用时:

( echo 'PS1="===COMMAND===\n"'; cat example ) | bash -i 2>&1 | ./formatter.pl

给出这个结果:

===
x=3
===
echo "$x"
---
3
===
y=$(($x+1))
===
echo "$y"
---
4
===

===

===
while [ "$y" -gt "0" ]
do
    echo $y
    y=$(($y-1))
done
---
4
3
2
1
===
exit
于 2016-07-26T19:46:26.627 回答
-1

代替 pidfiles,只要您的脚本具有唯一可识别的名称,您就可以执行以下操作:

  #!/bin/bash
COMMAND=$0
# exit if I am already running
RUNNING=`ps --no-headers -C${COMMAND} | wc -l`
if [ ${RUNNING} -gt 1 ]; then
  echo "Previous ${COMMAND} is still running."
  exit 1
fi
... rest of script ...
于 2016-07-29T09:22:12.837 回答