10

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?

Martin Ender
  • 8,774
  • 1
  • 34
  • 60
Sayak
  • 121
  • 1
  • 4
  • 1
    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 08 '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 08 '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 08 '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 08 '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 08 '16 at 16:39
  • Thank you Jason. I really appreciate your help. It works now – Sayak Mar 08 '16 at 16:43
  • @JasonB, Please repost your comment as an answer, so the Q/A makes sense and can be referenced. –  Mar 09 '16 at 14:54

1 Answers1

12

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"]

enter image description here

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.

Jason B.
  • 68,381
  • 3
  • 139
  • 286