【问题标题】:How to pass multi-word space-divided string value as separate arguments to the program in expect script?如何将多字空格分隔的字符串值作为单独的参数传递给期望脚本中的程序?
【发布时间】:2013-04-06 05:32:58
【问题描述】:

假设我有一个简单的expect 脚本(simple.exp):

set command "ls -l somedir"
spawn $command
interact

执行此脚本会导致错误,因为expect 将 ls -l(带有空格的整个字符串)视为命令而不是 ls 作为命令和 -l 作为选项:

expect -f simple.exp
spawn ls -l
couldn't execute "ls -l somedir": no such file or directory
     while executing
"spawn $command"
     (file "simple.exp" line 2)

我想要的是类似于bash 的行为,它首先处理字符串并将其分解为不同的参数以启动命令:

bash -c "ls -l somedir"

请注意,为简单起见,变量command 在脚本中进行了硬编码。在实际脚本中,它作为参数提供(任意命令行字符串)。

【问题讨论】:

    标签: expect


    【解决方案1】:

    解决方案的提示在this question 的答案中(expect 使用tcl 语言):

    set command "ls -l somedir"
    spawn {*}$command
    interact
    

    {*} 语法将以下字符串拆分为空格分隔的单词。

    【讨论】:

      【解决方案2】:

      最安全的命令是使用Tcl的list命令。例如:

      #!/usr/bin/expect
      set cmd [list ls -l "a b c.txt"]
      if { [package vcompare $tcl_version 8.5] < 0 } {
          eval spawn -noecho $cmd
      } else {
          spawn -noecho {*}$cmd
      }
      expect eof
      

      【讨论】:

      • 虽然我对自己首先找到的答案感到满意,但我接受你的答案,因为由于 TCL 的不同版本,它帮助我在更广泛的跨平台环境中解决了问题。感谢您的回答。
      【解决方案3】:

      这行得通。

      #!/usr/bin/expect
      
      set command "ls"
      set parameter "-la"
      set prompt ":~"
      spawn $command $parameter
      expect $prompt
      

      【讨论】:

      • 我更新了描述以避免假设 command 是硬编码的。因此,你不知道什么是命令名,什么是参数——command 是任意命令行。另请参阅 bash 示例 - 它解析用户提供的任何内容。
      【解决方案4】:

      如果你有一个 bash 字符串变量用作期望脚本的参数,你可以尝试使用 lrange:

      set command [lrange $argv x y]
      

      其中 x 和 y 是字符串变量中参数的开始和结束。
      例如:
      如果你的字符串变量是

      myvariable="hello how are you?"
      

      你正在像这样使用它:

      ./shellscript $myvariable
      

      那么您期望的脚本行将如下所示

      set command [lrange $argv 0 3]
      

      您可以在期望脚本中的任何位置使用 $command。它会根据需要包含空格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-14
        • 2017-04-25
        • 2016-01-08
        • 1970-01-01
        • 2022-12-09
        相关资源
        最近更新 更多