2

I am testing out Expect to get a basic template working. I have created a demo bash script which asks a few questions and outputs the inputs to a file.

When I execute the .exp file directly or through "expect FILENAME", or even when using autoexpect, I get the errors below that suggests it was not interpreted correctly(expected .exp file?). What should I do to get Expect with a bash script working?

  • I am testing using Ubuntu through WSL as the OS and CMD(bash is executed to use WSL and normal bash commands usable so not sure if this has any effect.).

Expect file:

#!/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

Bash shell file:

#!/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"

Output:

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

1 Answers1

5

You have a DOS (CRLF) line endings in your bash script, test-interactive.sh. This is most likely because you developed this script in a editor in Windows which by default ends lines with \r\n instead of the \n endings in *nix machines. As such when the script is run, it chokes on the extra \r which you are seeing below. Clean up your script before running by doing

dos2unix test-interactive.sh
Inian
  • 12,807