无法从shell脚本调用Openscad -D命令行

时间:2016-11-20 16:29:09

标签: bash command-line openscad

我在Ubuntu linux上使用openscad命令从命令行生成模型。我最终成功运行了openscad命令,使用-D参数覆盖变量值:

$ openscad -o output.stl -D 'param1="name1"' -D 'param2="name2"' openscad-script.scad

编辑:请注意我们必须传递-D参数的方式,单引号和双引号都必须存在,因为Openscad documentation

但是当我生成&从shell脚本执行相同的命令,openscad失败,错误:

$ ./myscript.sh value1 value2 
  

错误:行 XX 中的分析器错误:语法错误无法解析文件   'openscad-script.scad'!

XX =文件的最后一行。

这是bash脚本

#!/bin/bash
# run openscad command
param1="-D 'param1=\"$1\"'"
param2="-D 'param2=\"$2\"'"
echo "openscad -o $1-$2.stl $param1 $param2 openscad-script.scad"
openscad -o $1-$2.stl $param1 $param2 openscad-script.scad

这看起来很简单,我仍然无法弄清楚opencad在运行命令时失败的原因。

感谢您的帮助,

编辑:我找到了让它运转的方法,可能不是最好的

#!/bin/bash
# run openscad command
param1="-D 'param1=\"$1\"'"
param2="-D 'param2=\"$2\"'"
command = "openscad -o $1-$2.stl $param1 $param2 openscad-script.scad"
eval $command

2 个答案:

答案 0 :(得分:5)

如果您的命令行是:

#!/bin/bash
openscad \
  -o "$1-$2.stl" \
  -D "param1=\"$1\"" \
  -D "param2=\"$2\"" \
  openscad-script.scad

...然后执行此操作的正确脚本将是:

#!/bin/bash

args=( -o "$1-$2.stl" )
args+=( -D "param1=\"$1\"" )
args+=( -D "param2=\"$2\"" )

openscad "${args[@]}" openscad-script.scad

......或者,如果你真的想因为某种原因在多行上建立东西:

openscad

'param1="name1"' # becomes the C string "param1=\"name1\"" 字面上无法知道命令行中是否使用了单引号或双引号,因此没有强制要求单引号的方法。而且,shell引用是逐个字符的属性!也就是说:

param1='"name1"' # becomes the C string "param1=\"name1\"", same as above

导致完全相同的字符串被传递为:

param1='"'name1'"' # becomes the C string "param1=\"name1\"", same as above

name1

......当这些值都是常数时。但是,当$1替换为类似set -- name1; IFS=0123456789 "param1=\"$1\"" # becomes the C string "param1=\"name1\"", as above 'param1="$1"' # becomes the C string "param1=\"$1\"", not substituting name1 # ...and, as an example of something to look out for: param1='"'$1'"' # becomes TWO C strings, "param1=\"name" and "\"", due to bad quoting # ...the IFS above makes it split on numbers; by default this risk would happen with spaces 之类的内容时,根据所使用的引号类型,其含义会有所不同:

wave.open(...)

答案 1 :(得分:3)

撰写param1="-D 'param1=\"$1\"'", 我想你以后期待$param1, 运行openscad ... $param1命令时,将重新评估嵌入的双引号。但不,那不会发生。

为了达到你想要的效果,一个可行且干净的解决方案是使用Bash数组:

#!/bin/bash
params=(-D param1="\"$1\"" -D param2="\"$2\"")
printf '%q ' openscad -o "$1-$2".stl "${params[@]}" openscad-script.scad; echo
openscad -o "$1-$2".stl "${params[@]}" openscad-script.scad

我还引用了$1-$2,因为建议用它来阻止通配和分词。