chungkim271
chungkim271

Reputation: 967

expect script: set the output of ls command to a variable

I'm new to shell scripting and navigating different script languages.

I'm writing an expect script where I want to set the output of a ssh ls command to a variable to loop through, like the following bash script

#!/bin/bash
var=$(ssh user@host ls path | grep 'keyword')

echo $var

for x in $var;
# do stuff 
done

But I'm not sure how to do this in an expect script. Other examples I searched seem to be setting the output of send to a variable--is this the route?

Thanks for your help.

Upvotes: 2

Views: 6662

Answers (1)

glenn jackman
glenn jackman

Reputation: 246774

Capturing the output of a sent command into an expect variable is actually a PITA. The captured output contains the command and the prompt: suppose your prompt is "> " and you send the date command. Expect will see this:

"date\r\nTue Nov 15 11:34:16 EST 2016\r\n> "

So you need to do this to capture the output:

send -- "date\r"
expect -re {^[^\n]+\n(.*)\r\n> $}
set output $expect_out(1,string)

In that complicated pattern:

  • ^[^\n]+\n will match the command you send (up to the first newline) -- this is date\r\n
  • (.*)\r\n is the output of the command (up to the last line ending)
    • expect will store the captured text in the variable expect_out(1,string)
  • > $ is where you match your prompt.

So your program will be:

#!/usr/bin/env expect
spawn ssh user@host
expect -re {\$ $}      ;# regular expression to match your prompt

send -- "ls path | grep keyword\r"
expect -re {^[^\n]+\n(.*)\r\n$ $}
set output $expect_out(1,string)

send -- "exit\r"
expect eof

puts $output

Upvotes: 4

Related Questions