无法在 bash shell 中打印数组

Unable to print array in bash shell

我一直在 windows 上使用 tcl shell,但是在 bash 上协助某人时发现了一个奇怪的问题:

export SERVER_HOSTNAME=server1
export USERNAME=root
export PASSWORD=pswd
export LOG_FILE="a.log"
export LOG_PATH="$env(LOG_PATH)"
export log_search_pattern="Filterable_data"


/usr/bin/expect<<EOF
set lineNum {}
set SERVER_HOSTNAME "$env(SERVER_HOSTNAME)" 
set USERNAME "$env(USERNAME)" 
set PASSWORD "$env(PASSWORD)" 
set LOG_FILE "$env(LOG_FILE)"   
set log_search_pattern "$env(log_search_pattern)"
set timeout -1  
spawn ssh "$USERNAME@$SERVER_HOSTNAME"

expect  "assword:"  
puts "$expect_out(buffer)"  
parray expect_out
send  "$PASSWORD\r" 
expect "#"
puts "$expect_out(buffer)"
send  "grep -n $log_search_pattern  $LOG_PATH/$LOG_FILE|tail -1\r"  
expect eof
EOF 

现在的问题是以下命令:

puts "$expect_out(buffer)"
prints -> (buffer)

但打印整个缓冲区内容

parray expect_out

我还尝试添加以下行:

set a(1) val1
set a(2) val2
puts $a(1)
puts $a(2)
parray a

它打印了:

(1)
(2)
a(1) = val1
a(2) = val2

我尝试了各种组合来让 puts $a(1) 打印 val1 但它总是打印 (1)。

这样做的正确方法是什么?

变量在 HEREDOC 秒内展开。如果你想避免你需要引用部分或全部开始 HEREDOC 标记(即 <<'EOF')(但不是结束标记)。

来自 bash 参考手册中的 Here Documents

The format of here-documents is:

<<[-]word
        here-document
delimiter

If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded.

所以当你有:

puts "$expect_out(buffer)"

HEREDOC 中并期望 expect 看到它实际看到的文字字符串:

放置(缓冲区)

因为 shell 已经为您删除了引号并扩展了 $expect_out 变量。