I have the following in an expect script

spawn cat version
expect -re 5.*.*
set VERSION $expect_out(0,string)
spawn rpm --addsign dist/foo-$VERSION-1.i686.rpm

The cat command is getting the version correctly however it appears to be adding a new line. Since I expect the output to be the following:


but am getting including the error at the begining the following:

cannot access file dist/foo-5.x.x

Why is expect adding a new line to the cat command output and is there any way to have this not be done or to fix the output of the cat command?

  • What are the contents of the file and what do you need? TCL can read files without spawning cat...
    – thrig
    Jun 12, 2017 at 13:59
  • it's not cat that's adding a newline, it's the rpm command that's outputting the error
    – Jeff Schaller
    Jun 12, 2017 at 14:03
  • @thrig the contents of the file just say 5.x.x no other text in the file.
    – jgr208
    Jun 12, 2017 at 14:22

3 Answers 3


TCL can read a file directly without the complication of spawn cat:

#!/usr/bin/env expect

# open a (read) filehandle to the "version" file... (will blow up if the file
# is not found)
set fh [open version]
# and this call handily discards the newline for us, and since we only need
# a single line, the first line, we're done.
set VERSION [gets $fh]

# sanity check value read before blindly using it...
if {![regexp {^5\.[0-9]+\.[0-9]+$} $VERSION]} {
    error "version does not match 5.x.y"

puts "spawn rpm --addsign dist/foo-$VERSION-1.i686.rpm"

You most likely have a newline character at the end of your version file, so expect isn't so much adding a newline as it is blindly doing what you told it to. IMHO, it would be easier to adjust the expect script to strip out any newlines before spawning the rpm command, and it would ensure you don't run into this issue again if a different edit put the terminating newline back even after you've removed it.

Even if you don't have a terminating newline in the version file, I woud still advise you to add a strip() call (adjusting to the correct syntax for expect, of course) to handle this situation.


As thrig says, you should read the file directly. Also, using cat, as John says there will be a newline at the end of the file, and this will become \r\n (carriage-return, newline) on passing through the pty of spawn. So you can change your regex pattern to only capture upto these characters:

expect -re "(5.*)\r\n"
set VERSION $expect_out(1,string)

Note how we ask for index 1, the capture (), not 0, the whole pattern match.

Alternatively, you can remove the whitespace with the tcl command

set VERSION [string trim $expect_out(0,string)]

Note, you are confusing glob and regexp patterns in your expect line: 5.*.* as a glob pattern will match your 5.x.x style of input. Using -re means you should just use regexp 5.* which matches all to the end.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .