如何将命令输出保存到变量

How to save command output to variable

我正在用 expect 编写脚本,想将命令的输出保存在变量中。那可能吗? 命令是

echo "text here"| base64

我知道我可以用 "set" 设置一个变量,但是

set var ["echo text here| base64"]

set var [ spawn "echo text here| base64"]

不起作用。这样我只是保存字符串而不是输出。

exec命令returns命令的输出。这使您可以将其设置为变量:

set var [exec echo "text here" | base64]

但是,您可以避免 echo:

set var [exec base64 << "text here"]

而在 Tcl 8.6 中,您可以完全跳过 运行 外部程序:

set var [binary encode base64 "text here"]

还有a base64 encoder in Tcllib:

package require base64
set var [base64::encode "text here"]