2016-09-19 157 views
1

我有以下任務執行。使用expect發送多個響應交互式Linux命令

  1. 運行Linux命令「ABC」,它會要求多響應
  2. 首先,有多個線,它是要求從1-10中選擇選項。以'run?'結尾,必須選擇1
  3. 第二,以'是/否'結束。總是'是'的迴應
  4. 三,輸入ID。從一個.txt文件取一個ID作爲輸入。每行有一個ID。
  5. 四,y/n。始終選擇「y」作爲迴應。

步驟2-5應循環運行,直到.txt文件中的所有ID都結束,步驟5將選擇「否」或僅退出。

Tried below code in Shell/expect but sometimes it skip the ID's from list or show blank value and sometimes get crash while running and throw error:

*child process exited abnormally 
    while executing 
"exec cat output.txt | grep -i -B2 "rows selected" > result.txt" 
    (file "./cmp-test.sh" line 31)* 

下面是代碼:

exec echo "" > output.txt 
log_file [pwd]/output.txt 
set f [open list.txt r] 
# list is the file name contain ID's 

set idlist [ split [ read $f ] "\n" ] 
close $f 

send_user "\n Running script.. \n" 

spawn <abc command> 
foreach ids $idlist { 
expect { 
    "run? " { send "1\r" } 
} 

expect { 
    "ACDIG: " { send "$ids\r" } 
} 

expect { 
    "n)?" { send "y\r" } 
} 

} 

exec cat output.txt | grep -i -B2 "rows selected" > result.txt 

回答

0

你也許並不需要期待這樣的:

while read -r id; do 
abc << "answers" 
1 
yes 
$id 
y 
answers 
done < ids.txt 

while read -r id; do 
    printf "%s\n" 1 yes "$id" y | abc 
done < ids.txt 

由於grep在其輸入中找不到給定模式,因此grep以非零狀態退出:這是「正常」grep退出狀態,但由於它不爲零,因此Tcl /預計認爲發生了錯誤。

0

嘗試包括在foreach循環內的spawn。例如:

#!usr/bin/expect 

exec echo "" > output.txt 
log_file -a output.txt 

set f [open list.txt r] 
set idlist [read $f] 
close $f 

send_user "\n Running script.. \n" 

foreach ids $idlist { 
    spawn <abc command> 

    expect "run? " 
    send "1\r" 

    expect "ACDIG: " 
    send "$ids\r" 

    expect "n)?" 
    send "y\r" 
} 

log_file 
catch {exec cat output.txt | grep -i -B2 "rows selected" > result.txt} 

希望在你的第二個額外空白expect不會導致任何問題。

此外,您是否在腳本結尾處關閉了log_file進程?

+0

其中是腳本讀取list.txt文件? –

+0

@anujtyagi這裏是腳本的其餘部分按要求。我很確定'read'自動地通過換行符分割輸入文件,所以'split'幾乎是多餘的。順便說一下,我添加了一個catch命令來擺脫那個惱人的grep錯誤... – 2016-09-20 16:49:16