5

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.

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.

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?

1
  • 2
    I'm not quite sure how to do this but I can tell you why it doesn't work. Every time you call system() you are executing a new shell which exits immediately after the command is done. Commented Jul 23, 2010 at 21:11

2 Answers 2

6

If all you need to do is set environment variables, do this in MATLAB:

>> setenv('var','somepath')
>> system('echo $var')
Sign up to request clarification or add additional context in comments.

2 Comments

Good to know that they finally implemented a (pseudo-)setenv.
@rubenvb: Really? I guess the last time I was looking for this function must have been 5.3 then. Time flies.
3

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.

# 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 "$0"
echo "$3"
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.