# How to run a shell script from inside Mathematica

I have a very basic question. I have a shell file test.sh that prints let's say Yeah to a file called output.txt:

#!/bin/sh

echo "Yeah" > output.txt


I am running the Run command from the notebook:

Run["sh test.sh"]


But it is not creating the file output.txt. Can anyone tell me please what is going wrong?

• It works for me, are you looking in the right directory? When I run it Run["sh test.sh"] I get an output 0, and the output.txt shows up in the same directory. – Jason B. Mar 8 '16 at 16:21
• Thank you Jason but it is a little strange. I am getting an output 0 only when I specify the entire path to test.sh (though both the notebook and test.sh are in the same directory). But even then I do not see output.txt in the same directory. So Run["sh /Users/sxm016/Documents/Alignment/Alignment_ras_sos/March_\ 2016_ras_Gauss_multivariate/Bistable_traj/test.sh"] gives me an output 0 but no file named output.txt in the same directory – Sayak Mar 8 '16 at 16:28
• That is strange. What is the output from Directory[]? Perhaps the output.txt file is going somewhere in Mathematica's path? – Jason B. Mar 8 '16 at 16:32
• Thank you so much. That is exactly what is happening. When I typed Directory[] it showed me the path to my home not the current directory. Thank you. Can you please tell me how to change the mathematica path ? – Sayak Mar 8 '16 at 16:37
• you want SetDirectory[]. I actually have a line in my /home/jason/.Mathematica/Kernel/init.m file to say SetDirectory["~/Documents/Mathematica"]; so that I always start in that directory – Jason B. Mar 8 '16 at 16:39

The issue here is that when Mathematica executes an external system command, at least on Linux, it does so from the current directory. You can verify this via

Directory[]
Run["! echo \$PWD > file.txt"];
FilePrint["file.txt"]


which is my default working directory. I actually have a line in my

/home/jason/.Mathematica/Kernel/init.m

file that says SetDirectory["~/Documents/Mathematica"]; so that I always start in that directory.

• Well done, thank you! – user9660 Mar 9 '16 at 15:40
• @Louis Absolutely, it's always an open question what to do when a question is answered in the comments but it doesn't get closed. – Jason B. Mar 9 '16 at 19:18
• Yeah, I did that and it works. Thanks Jason. You saved me time – Sayak Mar 10 '16 at 16:15
• @Sayak - Glad to help. If that answers the question you could mark it as solved, then it won't be in the list of unanswered questions. – Jason B. Mar 10 '16 at 16:18