希望有 Tcl、Expect 和 Bash 知識的人能夠指導我進行以下操作:
我正在嘗試使用 CTRL-D 鍵盤快捷鍵使用 for 回圈和陣列列印出每一行上的用戶輸入,直到 EOF(檔案結尾)。但是,結果不如預期,我不確定第 22 行的語法應該是什么,因為陣列索引似乎沒有注冊變數i
提出“用戶:${inputs_array[$i]}”
print_inputs.sh
#!/bin/bash
# While Loop to get user inputs
echo '======For User Inputs======'
while read line
do
if [ "${line}" == '' ]
then
continue
else
inputs_array=("${inputs_array[@]}" "$line")
fi
done
# Prints out using Tcl script
echo '======Prints out======'
{
/usr/bin/expect << EOF
for {set i 0} {\$i < ${#inputs_array[@]}} {incr i} {
puts "User: ${inputs_array[$i]}"
}
EOF
}
結果:
======For User Inputs======
Sad
Happy
======Prints out======
User: Sad
User: Sad
下面是我目前使用的 bash 和 Tcl 版本:
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
% puts $tcl_version
8.5
提前致謝!
uj5u.com熱心網友回復:
考慮一下 Donal 的建議:這不需要是一個混合語言程式。然而:
首先,使用 bash 的readarray命令將輸入行讀取到陣列中:while用這個命令替換 bash回圈:
readarray -t inputs_array
一個警告:這不會像在陣列中那樣過濾掉空行。
其次,expect 不能訪問 shell 變數。您需要通過環境共享變數。但是,環境變數不能是陣列。我建議這樣做:
export array_contents
array_contents=$(printf '%s\n' "${inputs_array[@]}")
# Prints out using Tcl script
echo '======Prints out======'
# Note the heredoc word is quoted.
/usr/bin/expect << 'EOF'
set inputs [split $env(array_contents) \n]
foreach input $inputs {
puts "User: $input"
}
EOF
通過這些更改,輸出看起來像
$ bash print_inputs.sh
======For User Inputs======
foo
bar
baz
======Prints out======
User: foo
User: bar
User: baz
或者,使用程式化輸入
$ { echo foo; echo bar; echo baz; } | bash print_inputs.sh
======For User Inputs======
======Prints out======
User: foo
User: bar
User: baz
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/406187.html
標籤:
