bash 脚本中类似`expect`的行为

Pet*_*ter 6 bash

我有一个脚本(让我们命名它parent.sh),它根据输入参数调用其他一些脚本。

最后,它调用脚本child.sh
child.sh请求用户输入,以防它发现某些文件已经存在:

"Would you like to replace the configuration file with a new one? (Yes/No/Abort): "
Run Code Online (Sandbox Code Playgroud)

现在,我想这样做是为了模拟的按键“Y” /“Y”里面parent.sh的脚本,以便始终覆盖文件。

无法使用expect.

我怎样才能做到这一点?

mar*_*iux 1

虽然manatwork已经评论说这是一个有效的解决方案,但从程序员的角度来看,我会进行修补yes | child.sh以能够处理这个用例。child.sh

比如添加一个--force不提示但总是覆盖文件的选项。

但要回答你的问题的主题,并得到更多expect类似的东西,而不仅仅是y通过管道点火:

#!/bin/bash

fifo=fifo

mkfifo ${fifo}

exec 3<> ${fifo}

expect="Would you like to replace the configuration file with a new one? (Yes/No/Abort): "
answer="y"

while IFS= read -d $'\0' -n 1 a ; do
    str+="${a}"

    if [ "${str}" = "${expect}" ] ; then
        echo "!!! found: ${str}"
        echo ">>> sending answer: ${answer}"
        echo "${answer}" >&3
        unset str
    fi

    if [ "$a" = $'\n' ] ; then
        echo -n "--- discarding input line: ${str}"
        unset str
    fi
done < <(./child.sh <${fifo})

rm ${fifo}
Run Code Online (Sandbox Code Playgroud)

我只是写了这个..所以它并不是真正的故障安全或针对解决特定问题进行了测试..所以使用时需要您自担风险 8) 在某些条件下可能会出现一些行缓冲问题..

但至少它在我的测试场景中有效。