如何在vagrant的测试中使用命令运行bash脚本?

时间:2022-05-16 00:07:52

Running commands or script lines with simple tests, like -e, in vagrant using the ssh subcommand works fine (e.g.

使用ssh子命令在vagrant中使用简单测试(如-e)运行命令或脚本行正常工作(例如

vagrant ssh -c 'if ! [ -e file.deb ] ; then wget http://a.b/file.deb; fi'

as soon as string comparison and command execution bash quoting gets involved, complexity immediately rises to the sky. I tried

一旦字符串比较和命令执行bash引用被涉及,复杂性立即上升到天空。我试过了

  • escaping strings, but that doesn't seem to work in general (complexity of escaping of escaping of escaping ... in bash is just inacceptable)
  • 逃避字符串,但这似乎不起作用(逃避逃避逃逸的复杂性......在bash中是不可接受的)

  • writing everything in a script file with cat <<EOF > file [code]EOF idiom, e.g.

    使用cat << EOF> file [code] EOF idiom在脚本文件中写入所有内容,例如

    vagrant ssh -c 'cat <<EOF > fetch.sh \
    #!/bin/bash \
    if [ "$(md5sum file.deb | cut -d \" \" -f 1)" != "d757d51819f8f945ae7715b532ab8d2e" ] ; then wget http://a/b/file.deb; fi \
    EOF'
    vagrant ssh -c 'bash ./fetch.sh'
    

    causes ./fetch.sh: line 1: syntax error near unexpected token `if'

    导致./fetch.sh:第1行:意外令牌附近的语法错误`if'

  • the failure of the cat EOF idiom implies failure of any sort of script created in vagrant (python, groovy, etc. would suffer from the same incapacity of bash to provide usable string quoting/be usable at all)
  • 猫EOF成语的失败意味着在流浪汉中创建的任何类型的脚本失败(python,groovy等等都会遭受同样的bash无能力提供可用的字符串引用/可用)

Is there any way to execute script code with complex statements in tests inside a vagrant box? Do I seriously need to transfer the script via the localhost interface (using FTP or something similar)?

有没有办法在流浪盒内的测试中使用复杂语句执行脚本代码?我是否真的需要通过localhost接口(使用FTP或类似的东西)传输脚本?

1 个解决方案

#1


With knowledge of How to use SSH to run a shell script on a remote machine? it's possible to connect to vagrant using

了解如何使用SSH在远程计算机上运行shell脚本?可以使用连接到vagrant

ssh -p [port] -i [keyfile] vagrant@localhost 'bash -s' < script.sh

(with [port] and [keyfile] retrieved from vagrant ssh-config) and the script code put in script.sh.

(使用[port]和[keyfile]从vagrant ssh-config中检索)并将脚本代码放在script.sh中。

The port can change if multiple vagrant instances are running (each starting its own SSH server), so you might need to parse vagrant ssh-config.

如果多个vagrant实例正在运行(每个实例都启动自己的SSH服务器),端口可能会更改,因此您可能需要解析vagrant ssh-config。

#1


With knowledge of How to use SSH to run a shell script on a remote machine? it's possible to connect to vagrant using

了解如何使用SSH在远程计算机上运行shell脚本?可以使用连接到vagrant

ssh -p [port] -i [keyfile] vagrant@localhost 'bash -s' < script.sh

(with [port] and [keyfile] retrieved from vagrant ssh-config) and the script code put in script.sh.

(使用[port]和[keyfile]从vagrant ssh-config中检索)并将脚本代码放在script.sh中。

The port can change if multiple vagrant instances are running (each starting its own SSH server), so you might need to parse vagrant ssh-config.

如果多个vagrant实例正在运行(每个实例都启动自己的SSH服务器),端口可能会更改,因此您可能需要解析vagrant ssh-config。