我正在测试 Expect 以使基本模板正常工作。我创建了一个演示 bash 脚本,它会询问一些问题并将输入输出到文件中。
当我直接或通过“expect FILENAME”执行 .exp 文件时,甚至在使用 autoexpect 时,我都会收到以下错误,表明它没有被正确解释(预期的 .exp 文件?)。我应该怎么做才能让 bash 脚本运行 Expect?
期待文件:
#!/usr/bin/expect -f
set timeout -1
spawn /bin/bash "./test-interactive.sh"
# expect "*"
expect "Please fill in each prompt."
send -- "a\r"
expect "*"
send -- "b\r"
expect "Please fill in each prompt."
# expect "*"
send -- "c\r"
expect "*"
send -- "d\r"
expect eof
Run Code Online (Sandbox Code Playgroud)
Bash 外壳文件:
#!/bin/bash
_message="Please fill in each prompt."
echo $_message
read a
read b
echo $_message
echo -n "$ "
read x
echo -n "$ "
read y
echo ""
echo "Accepting following inputs"
echo $a
echo $b
echo $x
echo $y
echo ""
echo "a: $a b: $b x: $x y: $y" > output.txt
# read -p "Press enter to exit"
Run Code Online (Sandbox Code Playgroud)
输出:
spawn /bin/bash ./test-interactive.sh
./test-interactive.sh: line 2: $'\r': command not found
./test-interactive.sh: line 4: $'\r': command not found
Please fill in each prompt.
a
b
./test-interactive.sh: line 6: $'\r': command not found
': not a valid identifierne 7: read: `a
': not a valid identifierne 8: read: `b
./test-interactive.sh: line 9: $'\r': command not found
Please fill in each prompt.
c
d
./test-interactive.sh: line 11: $'\r': command not found
': not a valid identifierne 13: read: `x
': not a valid identifierne 15: read: `y
./test-interactive.sh: line 16: $'\r': command not found
Accepting following inputs
Run Code Online (Sandbox Code Playgroud)
您的bash
脚本中有一个 DOS (CRLF) 行结尾,test-interactive.sh
. 这很可能是因为您在 Windows 中的编辑器中开发了此脚本,默认情况下,该编辑器以 *nix 机器\r\n
中的\n
结尾而不是结尾。因此,当脚本运行时,它会因\r
您在下面看到的额外内容而窒息。在运行之前清理脚本
dos2unix test-interactive.sh
Run Code Online (Sandbox Code Playgroud)