How can I insert the *contents* of a string variable directly into my code?

5 ビュー (過去 30 日間)
Thomas
Thomas 2016 年 12 月 1 日
回答済み: Thomas 2016 年 12 月 2 日
I am working with git version control and would like to use the following function to commit my changes:
function gitCommit( str )
currDirectory = pwd;
cd(myScriptDirectory);
% Add all files and changes to git
!git add *
% Commit everything to repository with a message
!git commit -m str
cd(currDirectory);
end
Then, regardless of where I'm working, I could simply type:
gitCommit('This is my commit log');
and it will commit all of the modifications I've made to a script in myScriptDirectory to the local repository while also recording the log 'This is my commit log', negating the need for me to enter it later into a pop-up window. The problem is that, if I do this, then the log file will always read 'str' and not 'This is my commit log', as this code is incapable of actually taking the content of the str variable and passing that to the !git command. Instead, it always just passes 'str'. I have no idea how to accomplish this. Any tips?

採用された回答

Steven Lord
Steven Lord 2016 年 12 月 1 日
編集済み: Steven Lord 2016 年 12 月 1 日
Use the system function instead of the ! operator.
comment = 'Hello world!';
% leaving off the semicolon on the next line so you can see the result
commandToExecute = ['git commit -m ' comment]
system(commandToExecute)

その他の回答 (2 件)

Jorrit Montijn
Jorrit Montijn 2016 年 12 月 1 日
A dirty work-around is using eval() and just pasting everything you want to perform as a string. For example:
eval(['!git commit -m' str]);
However, if you do this, matlab will no longer be able to generate warning/error messages, as the code analyzer cannot interpret what is happening inside the eval() statement.

Thomas
Thomas 2016 年 12 月 2 日
This solution worked very well for me, thanks! I had to make one minor modification. I should enclose the string in double quotations (which I forgot to mention above). So I changed the line defining commandToExecute to:
commandToExecute = ['git commit -m "' str '"']

カテゴリ

Help Center および File ExchangeSource Control についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by