【问题标题】:invalid command name "cat". expect send [ ] at shell script无效的命令名称“cat”。期望在 shell 脚本中发送 []
【发布时间】:2016-01-14 05:00:29
【问题描述】:

我想在 shell 脚本中使用期望

我的代码在这里

#!/bin/sh

expect << EOF
send [cat hello]
EOF

此命令失败

命令名称“cat”无效

在执行“cat hello”时

从“发送 [cat hello]”中调用

但是,在期望提示符下发送 [cat hello] 命令成功

expect1.1> send [cat hello]
world
expect1.2> 

为什么我会输出不同的执行结果?

【问题讨论】:

    标签: shell expect


    【解决方案1】:

    expect shell 内:

    当您在expect shell 中时,无论何时给出任何可执行的 shell 命令,该命令都会被执行,就像您在终端中正常执行一样。

    expect1.1> ls
    A  B  C  D
    expect1.2> cat A
    I am A
    
    expect1.3> pwd
    /home/dinesh/test
    expect1.4>    
    

    如果你把它们放在方括号里,比如[cat A],与普通的命令调用不同,它仍然会执行shell命令并返回空字符串。

    expect1.4> set val [cat A]
    I am A
    
    expect1.5> puts "->$val<-"
    -><-
    expect1.6>
    

    如果您添加一个名称与任何 shell 命令等效的过程,则只会调用相应的命令。

    expect1.6> proc cat {input} {
    +> return "you passed $input\n"
    +> }
    expect1.7> cat A
    you passed A
    
    expect1.8> cat
    wrong # args: should be "cat input"
        while executing
    "cat "
    expect1.9> send [cat A]
    you passed A
    expect1.10>   
    

    除非设置了spawn_id(通过生成任何程序),否则Expect 将始终期望并分别向stdinstdout 发送命令。

    expect1.11> exp_internal 1
    expect1.12> expect hai
    
    expect: does "" (spawn_id exp0) match glob pattern "hai"? no
    

    正如您在调试输出中所见,exp0 仅指向 stdin

    expect程序被调用时

    当显式调用expect程序时,此时要执行任何shell命令,必须使用exec命令,否则会得到invalid command name error消息。

    expect << EOF
     send [exec cat hello]
    EOF
    

    输出:

    [dinesh@lab test]$ ./baek.sh
    I am A
    [dinesh@lab test]$
    

    现在,为什么会有这种差异?

    从技术上讲,当您使用expect shell 时,您可以在其中执行 shell 命令。

    【讨论】:

      猜你喜欢
      • 2016-07-07
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      • 2014-08-11
      相关资源
      最近更新 更多