我在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
这看起来很简单,但我仍然无法理解是什么使openscad在运行命令时失败。
谢谢你的帮助,
编辑:我找到了一个办法,也许不是最好的
#!/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
最佳答案
如果您想要的命令行是:
openscad -o name1-name2.stl -D 'param1="name1"' -D 'param2="name2"' openscad-script.scad
…那么正确的脚本是:
#!/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\""
结果与传递的字符串完全相同:
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