从bash脚本中向Octave函数传递参数

8
我在Octave中编写了一个函数,它以从文件中读取的一行(每次一行)作为输入参数。我使用一个bash脚本从文件中逐行读取数据,并将其作为参数传递给脚本内的Octave函数。
我的bash脚本看起来像这样:
#!/bin/bash  

while read line
do
  octave --silent --eval 'myOctaveFunc("${line}")'
done < "inFileName"

当我执行上述脚本时,Octave会抛出错误,例如:
error: called from:
error:   /usr/share/octave/3.2.3/m/miscellaneous/fullfile.m at line 43, column 11
error: evaluating argument list element number 2
error: evaluating argument list element number 1
error:   /usr/libexec/octave/packages/gsl-1.0.8/i386-redhat-linux-gnu-api-v37/PKG_ADD at line 47, column 1
error: addpath: expecting all args to be character strings
error: addpath: expecting all args to be character strings
error: addpath: expecting all args to be character strings
error: addpath: expecting all args to be character strings

等等等等...

我已经能够从命令行中运行带有输入参数的Octave脚本myOctaveFunc.m,比如helloWorld。但当我尝试从bash脚本中运行它时,问题就出现了。

我的问题是:
1. 我该如何在bash脚本中运行Octave函数?
2. 我正在使用gvim编辑bash脚本。当我输入调用Octave脚本的代码行时,我发现${line}的颜色与正常情况下不同。这是因为调用Octave函数时使用了''吗?如果是,我应该担心吗?


1
你如何在 Bash 脚本之外调用你的 Octave 脚本?如果你在 Bash 脚本中使用 "echo octave --silent ..." 而不是 "octave --silent",会看到什么? - Bruno De Fraine
@Bruno:在回显后调用Octave脚本的方式大致如下:octave --silent --eval 'myOctaveFunc(helloWorld)',而应该是 octave ... 'myOctaveFunc("helloWorld")'。我尝试过 octave ... 'myOctaveFunc(\"helloWorld\")'。这在bash中使用echo时可以正常工作,但在调用Octave脚本时失败了。 - Sriram
1个回答

13
单引号会防止shell替换变量的值:
octave --silent --eval "myOctaveFunc(\"$line\")"

如果Octave允许您使用单引号来引用字符串,代码看起来会更加清晰(在双引号内,单引号没有特殊含义):

octave --silent --eval "myOctaveFunc('$line')"

另外,在使用vim时,请确保将文件保存为Unix格式,这样每行就不会以回车符结尾::set ff=unix


另外,是否需要使用“:set ff = unix”选项?我正在Linux机器上工作,并确保每次从Windows返回时都进行“dos2unix”处理。 - Sriram
1
你没有告诉我们关于你的环境的任何信息,所以不需要。 - glenn jackman
当我运行 octave --silent --eval "dbEval(\"hello-world\")" 时,它会返回警告信息:warning: function 'dbEval' defined within script file '/home/max/octave-dollar/scripts/dbEval.m' - pwan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接