在 Matlab 中使用 bash shell
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3322374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using bash shell inside Matlab
提问by ali
I'm trying to put a large set of bash commands into a matlab script and manage my variables (like file paths, parameters etc) from there. It is also needed because this workflow requires manual intervention at certain steps and I would like to use the step debugger for this.
我正在尝试将大量 bash 命令放入 matlab 脚本并从那里管理我的变量(如文件路径、参数等)。它也是必需的,因为此工作流程需要在某些步骤手动干预,我想为此使用步骤调试器。
The problem is, I don't understand how matlab interfaces with bash shell.
I can't do system('source .bash_profile')to define my bash variables. Similarly I can't define them by hand and read them either, e.g. system('export var=somepath')and then system('echo $var')returns nothing.
问题是,我不明白 matlab 如何与 bash shell 接口。我无法system('source .bash_profile')定义我的 bash 变量。同样,我也无法手动定义它们并读取它们,例如system('export var=somepath'),然后不system('echo $var')返回任何内容。
What is the correct way of defining variables in bash inside matlab's command window? How can I construct a workflow of commands which will use the variables I defined as well as those in my .bash_profile?
在 matlab 的命令窗口内的 bash 中定义变量的正确方法是什么?我如何构建一个命令工作流,该工作流将使用我定义的变量以及我的 .bash_profile 中的变量?
回答by Gilead
If all you need to do is set environment variables, do this in MATLAB:
如果您需要做的只是设置环境变量,请在 MATLAB 中执行此操作:
>> setenv('var','somepath')
>> system('echo $var')
回答by tilo
Invoke Bash as a login shell to get your ~/.bash_profile sourced and use the -c option to execute a group of shell commands in one go.
调用 Bash 作为登录 shell 来获取您的 ~/.bash_profile 来源,并使用 -c 选项一次性执行一组 shell 命令。
# in Terminal.app
man bash | less -p 'the --login option'
man bash | less -p '-c string'
echo 'export profilevar=myProfileVar' >> ~/.bash_profile
# test in Terminal.app
/bin/bash --login -c '
echo "##代码##"
echo ""
echo "$@"
export var=somepath
echo "$var"
echo "$profilevar"
ps
export | nl
' zero 1 2 3 4 5
# in Matlab
cmd=sprintf('/bin/bash --login -c ''echo "$profilevar"; ps''');
[r,s]=system(cmd);
disp(s);

